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

Jquery中attr()与prop()方法的差异

2014-01-22 13:59 281 查看
1.prop(propertyName)                                                                                                 Returns:String  or  Boolean

官方描述:Get the value of a property for the first element in the set of matched elements.(获取匹配元素集合中第一个相匹配元素的值)

如果the value of protopy 没有被设置,则返回undefined.

注意:在IE6,7,8中试图通过此方法来改变通过HTML或者已经存在于HTML document中的input的元素的属性将会报错。

2.Attributes 与Properties 区别

在Jquery1.6之前,还没有prop()方法,我们通过attr()可以获取元素的属性值,但是这样会产生一些问题;

比如官方例子:

<input type="checkbox" checked="checked" />
elem.checked                               //return true(Boolean)
elem.getAttribute("checked")               //return "checked"
$(elem).attr("checked")                    //(1.6)return "checked"
$(elem).attr("checked")                    //(1.6.1+)return "checked"
$(elem).attr("checked")                    //(pre-1.6)return true


Jquery1.6之后呢,出现了porp()这个方法

  

$(element).prop("checked")           //return true


总结:就是说,对于
selectedIndex
tagName
nodeName
nodeType
ownerDocument
defaultChecked
,
and 
defaultSelected
元素,我们需要使用prop方法还获取其是boolean值,对于attr方法,我们修改的是其普通属性。在360急速模式下,使用attr("selected")将会产生错误,但调试器不会报错。此错误在IE10,chrome,firefox,opera中都不存在。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery checkbox html 360