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属性的值已经发生改变: