prop 与attr的区别

来源:互联网 发布:保密局检查软件 编辑:程序博客网 时间:2024/04/18 19:52
.prop()

1、.prop( propertyName )
获取匹配集合中第一个元素的Property的值
2、
.prop( propertyName, value )
.prop( map )
.prop( propertyName, function(index, oldPropertyValue) )
给匹配元素集合设定一个或多个属性

.prop()和 .attr()区别

下面是关于jQuery1.6和1.6.1中Attributes模块变化的描述,以及.attr()方法和.prop()方法的首选使用

Attributes模块的变化是移除了attributes和properties之间模棱两可的东西,但是在jQuery社区中引起了一些混乱,因为在1.6之前的所有版本中都使用一个方法(.attr())来处理attributes和properties。但是老的.attr()方法有一些bug,很难维护。jQuery1.6.1对Attributes模块进行了更新,并且修复了几个bug。

elem.checked true (Boolean) Will change with checkbox state
$(elem).prop("checked") true (Boolean) Will change with checkbox state
elem.getAttribute("checked") "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked")(1.6) "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked")(1.6.1+) "checked" (String) Will change with checkbox state
$(elem).attr("checked")(pre-1.6) true (Boolean) Changed with checkbox state

if ( elem.checked )
if ( $(elem).prop("checked") )
if ( $(elem).is(":checked") )

这三个都是返回Boolean值。


为了让jQuery1.6中的.attr()方法的变化被理解的清楚些,下面是一些使用.attr()的例子,虽然在jQuery之前的版本中能正常工作,但是现在必须使用.prop()方法代替:

jQuery学习之prop和attr的区别

首先,window或document中使用.attr()方法在jQuery1.6中不能正常运行,因为window和document中不能有attributes。它们包含properties(比如:location或readyState),必须使用.prop()方法操作或简单地使用javascript原生的方法。在jQuery1.6.1中,window和document中使用.attr()将被自动转成使用.prop,而不是抛出一个错误。

其次,checked,selected和前面提到的其它boolean attributes,因为这些attributes和其相应的properties之间的特殊关系而被特殊对待。基本上,一个attribute就是以下html中你看到的:

<input type=”checkbox” checked=”checked”>  

 

boolean attributes,比如:checked,仅被设置成默认值或初始值。在一个checkbox的元素中,checked attributes在页面加载的时候就被设置,而不管checkbox元素是否被选中。

0 0
原创粉丝点击