JS中attr和prop属性的区别

JavaScript09

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()

$('.qhdxImg').attr({src:'images/qhdx-2.png'})

显示单词写错了。

错误提示也是写.arrt is not a function.检查一下代码。