jquery中prop和attr的区别有哪些
来源:互联网 发布:内部沟通软件 编辑:程序博客网 时间:2024/05/12 12:18
一. 特性(properties)和属性(attributes)有何区别?
DOM对象大部分的property都有对应的attribute,名字也基本一样(也有例外,如“class”这个attribute对应的property名字为“className”),这些property也和其对应的attribute保持一样的状态或值。但一些Boolean类型的属性(如checked, selected, disabled等)有些特殊,其attribute只保留初始值(默认值), property才是当前最新的状态或值。如一个默认勾选的checkbox,当你在页面去除勾选的时候,checked这个property已由true变为false,而checked这个attribute仍然保持“checked”这个初始值。由此可见attribute和property完全不是同一个东西,但“通用”的attr方法似乎在某种程度上模糊了这个区别。
二. attr()和prop()有何区别?
使用prop的时候,返回值是标准属性,true/false,比如$('#checkbox').prop('disabled'),不会返回“disabled”或者“”,只会是true/false。当然赋值的时候也是如此。使用attr,如disabled='disabled'时,为true,没有选中时,则为undefined。如此,我们便统一了所有操作,无论是从语法上还是语义上。
.prop()方法应该被用来处理boolean attributes/properties以及在html(比如:window.location)中不存在的properties。其他所有的attributes可以而且应该继续使用.attr()方法来进行操作。
三、什么时候使用attr(),什么时候使用prop()?
1、添加属性名称该属性就会生效应该使用prop();
2、是有true,false两个属性使用prop();
3、其他则使用attr();
4、简单的说,那些只添加属性名不添加属性值就会生效,或者是,只存在true/false的属性就需要使用prop()方法,比如selectedIndex
,tagName
, nodeName
, nodeType
,ownerDocument
, defaultChecked
, 和defaultSelected
。
参考资料: jquery中prop和attr的区别 http://www.studyofnet.com/news/319.html
- jquery中prop和attr的区别有哪些
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jQuery中prop和attr的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jquery中attr和prop的区别
- jQuery中prop和attr的区别
- 解决ORA-12519: TNS:no appropriate service handler found问题
- MySql导入导出数据库(含远程导入导出)
- 存储过程同函数的区别
- codeforces 401B - Sereja and Contests
- Oracle批量清空所有表数据(置空数据库)
- jquery中prop和attr的区别有哪些
- 黑马程序员—Java基础学习笔记之数据类型转换(自动转换和强制转换)
- 单件模式 java
- 修改对象私有属性
- JSP页面的异常处理
- JAVA基础之IO读写
- Android 进程状态的概念
- 最大公约数
- Exercise 14: 提示和传参