您的位置:首页 > Web前端 > JQuery

jquery中的attributes和properties

2016-06-29 22:46 471 查看
attributes和properties之间的差异在特定情况下是很重要。jQuery 1.6之前 ,
.attr()
方法在取某些
attribute 的值时,会返回 property 的值,这就导致了结果的不一致。从 jQuery 1.6 开始, 
.prop()
方法
方法返回 property 的值,而
.attr()
 方法返回 attributes 的值。

例如, 
selectedIndex
tagName
nodeName
nodeType
ownerDocument
defaultChecked
,
和 
defaultSelected
应使用
.prop()
方法进行取值或赋值。 在jQuery1.6之前,这些属性使用
.attr()
方法取得,但是这并不是元素的
attr
属性。他们没有相应的属性(attributes),只有特性(property)。

例如,考虑一个DOM元素的HTML标记中定义的
<input type="checkbox" checked="checked" />
 ,并假设它是一个JavaScript变量命名的
elem
 :

elem.checked
true
 (Boolean) 将随着复选框状态的改变而改变
$(elem).prop("checked")
true
 (Boolean) 将随着复选框状态的改变而改变
elem.getAttribute("checked")
"checked"
 (String) 复选框的初始状态;不会改变
$(elem).attr("checked")
 (1.6)
"checked"
 (String) 复选框的初始状态;不会改变
$(elem).attr("checked")
 (1.6.1+)
"checked"
 (String) 将随着复选框状态的改变而改变
$(elem).attr("checked")
 (pre-1.6)
true
 (Boolean) 将随着复选框状态的改变而改变
根据W3C的表单规范 ,在
checked
属性是一个布尔属性
这意味着,如果这个属性(attribute)是目前存在, 即使,该属性没有对应的值,或者被设置为空字符串值,或甚至是"false",相应的属性(property)为true。 这才是真正的所有布尔属性(attributes)。

然而,要记住的最重要的概念是
checked
特性(attribute)不是对应它
checked
属性(property)。特性(attribute)实际对应的是
defaultChecked
属性(property),而且仅用于设置复选框最初的值。
checked
特性(attribute)值不会因为复选框的状态而改变,而
checked
属性(property)会因为复选框的状态而改变。因此,
 跨浏览器兼容的方法来确定一个复选框是否被选中,是使用该属性(property):

if ( elem.checked )


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


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

对于其他的动态属性,同样是true,比如 
selected
 和 
value
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: