JS中attr和prop属性的区别

JavaScript075

JS中attr和prop属性的区别,第1张

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”>

但它仅表示checked属性在页面加载的时候被设置成默认值或初始值,而不管checkbox元素是否被选中。 而通常 properties 是一个浏览器用来记录当前属性值的东西。正常情况下,properties反映它们相应的attributes。

  所以,当用户点击一个checkbox元素或选中一个select元素的一个option时,使得properties保持最新,但对应的attributes却不一定,它仅被浏览器用来保存该属性的初始值。

一个例子:

<input type="radio" id="RdMale" checked="checked" name="sex" value="male" /><label for="hRdMale">男</label>

<input type="radio" id="RdFemale" name="sex" value="female" /><label for="hRdFemale">女</label>

<button id="reSet">重置</button>

jQ代码

$("#reSet").click(function() {

$("input[name='sex']:first").attr("checked",true)

})

但这样写火狐浏览器不支持,

  添加属性名称该属性就会生效应该使用.prop()

$("input[name='sex']:first").prop("checked",true) //改成prop就成功了

  区别在于selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 以及defaultSelected 等属性需用.prop()方法。  添加属性名称该属性就会生效应该使用.prop()

attr不是单纯的键盘上的哪个键。

attr : 设置或返回被选元素的属性值。

attr 是 attribute 的缩写,有属性的意思,只不过 attr 是操作 html 文档节点属性,attr 在 js 中使用的是 setAttribute 和 getAttribute。attr 设置的属性值只能是字符串类型,如果不是字符串类型,也会调用其 toString() 方法,将其转换成字符串类型。attr 返回的也是字符串类型, 选中或禁用直接返回 checked,selected,disabled。否则返回undefined。