JQ-attr和prop区别使用:
- 对于HTML元素本身就带有的原生的固有属性,在处理时,使用prop方法。
- 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
都是获取在匹配的元素集中的第一个元素的属性值。
attr( attributeName, function(index, attr) ):允许为属性值设置一个函数返回值。
这个函数返回用来设置的值,this指向当前的元素。接收index 参数表示元素在匹配集合中的索引位置和html 参数表示元素上原来的 HTML 内容。
prop( attributeName, function(index, attr) ):attr效果相同。
以下是评分控件的部分代码:
//为每个td添加score属性并赋值,index表示搜索结果集中的每个td的索引位置
$('#trd td').attr('score', function (index) {
return (index + 1) * 20;//一共5个 1.20 2.40 3.60-----
});
$('input[type=checkbox]').prop('checked', function(key, val) {
return !val;
});
1. 当我们操作:<a href="http://www.baidu.com" target="_self" class="btn">百度</a>
a元素的DOM属性有“href、target和class",这些属性就是a元素本身就带有的属性,也是W3C标准里就包含有这几个属性,或者说在IDE里能够智能提示出的属性,这些就叫做固有属性。处理这些属性时,建议使用prop方法。
2. 当我们操作:<a href="#" id="link1" action="delete">删除</a>
a元素的DOM属性有“href、id和action”,很明显,前两个是固有属性,而后面一个“action”属性是我们自己自定义上去的,a元素本身是没有这个属性的。这种就是自定义的DOM属性。处理这些属性时,建议使用attr方法。使用prop方法取值和设置属性值时,都会返回undefined值。
像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果。具有 true 和 false 两个属性的属性,如 checked, selected 或者 disabled 使用prop()
//对于自定义属性,attr获取正确 <a id="a" action="s"></a>
// alert($('#a').attr('action'));//s
alert($('#a').prop('action')); //undefined 使用prop获取自定义属性获取错误,适用于原生固有属性的操作
$("#chk1").prop("checked") == false;
$("#chk2").prop("checked") == true;
$("#chk1").attr("checked") == undefined;
$("#chk2").attr("checked") == "checked";
//-------------------------------
$(function() {
// var s = $('#b').attr('checked');
// var s = $('#b').prop('checked'); //true
// alert(s);
// alert($('#f').attr('selected'));//selected
alert($('#f').prop('selected')); //true
})
END—