JS中attr和prop属性的区别

如题所述

window或document中使用.attr()方法在jQuery1.6之前不能正常运行,因为window和document中不能有attributes。prop应运而生了。

1、attr方法里面,最关键的两行代码,elem.setAttribute( name, value + “” )和ret = elem.getAttribute( name ),很明显的看出来,使用的DOM的API setAttribute和getAttribute方法操作的属性元素节点。

2、prop方法里面,最关键的两行代码,return ( elem[ name ] = value )和return elem[ name ],你可以理解成这样document.getElementById(el)[name] = value,这是转化成JS对象的一个属性。

举例说明:

html:

<input type="text" value="test" id="test"/>

js代码对比写法:

alert('attr(): '+$('#test').attr('value'));

alert('prop(): '+$('#test').prop('value'));

修改value后:

$('#test').change(function(){

    alert('attr(): '+$(this).attr('value'));

    alert('prop(): '+$(this).prop('value'));

});

运行结果:

1、attr竟然没有变化:

2、prop属性的值已经发生改变:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-05-16
attr和pop主要是来获取和设置元素属
区别如下:
对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
举一个例子:
<input id="chk1" type="checkbox" />是否可见
<input id="chk2" type="checkbox" checked="checked" />是否可见
像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。
$("#chk1").prop("checked") == false
$("#chk2").prop("checked") == true
如果上面使用attr方法,则会出现:
$("#chk1").attr("checked") == undefined
$("#chk2").attr("checked") == "checked"