您的位置:首页 > Web前端 > JQuery

jQuery中的attr()与prop()设置属性、获取属性的区别

2017-08-20 10:21 806 查看
jQuery中的attr()与prop()设置属性、获取属性的区别

一、checkbox的属性设置选中或不选中



举例,比如我们要获取checkbox的属性或者设置checkbox选中或不选中。

$("#editForm").find("input[type='checkbox']").attr("checked",false);  //非标准写法$("#editForm").find("input[type='checkbox']").attr("checked", true);  //非标准写法$("#editForm").find("input[type='checkbox']").attr("checked", "checked"); //通用写法,不推荐了

建议改为如下(标准写法):

$("#editForm").find("input[type='checkbox']").prop("checked", false);  //设置选中,推荐写法$("#editForm").find("input[type='checkbox']").prop("checked", true); //设置取消选中,推荐写法

(锋利的jQuery第二版,第149页)



总结建议:

获取和设置disabled、selected、checked这些属性时,应该使用prop()方法,不要使用attr()方法!!能够用prop()操作的尽量用prop()操作,不要用attr()操作。

二、attr()和prop()用法详解


※ 定义和用法

attr() / prop() 方法设置或返回被选元素的属性和值。

当该方法用于返回属性值时,则返回第一个匹配元素的值。

当该方法用于设置属性值时,则为匹配元素集合设置一个或多个属性/值对

$("img").attr({width:"150",height:"100"});

注意:prop() 方法应该用于检索属性值,例如 DOM 属性(如 selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected)。

提示:如需检索 HTML 属性,请使用 attr() 方法代替。

提示:如需移除属性,请使用 removeProp() 方法。

注意:不要使用该方法来移除诸如
style、id 或 checked 之类的 HTML 属性。请使用 removeAttr() 方法代替。(关于删除属性的函数方法,请参考本文末尾的链接有详细介绍)




※语法

返回属性的值:

$(selector).prop(property)
                            

设置属性和值:

$(selector).prop(property,value)

使用函数设置属性和值:

$(selector).prop(property,function(index,currentvalue))

设置多个属性和值:

$(selector).prop({property:value, property:value,...})

参数描述
property规定属性的名称。
value规定属性的值。
function(index,currentvalue)规定返回要设置的属性值的函数。
index -检索集合中元素的 index 位置。
currentvalue -检索被选元素的当前属性值。
示例&说明

以下面这段HTML代码为例:
<div id="n1">
<p id="n2" class="demo test" data-key="UUID" data_value="1235456465">CodePlayer</p>
<input id="n3" name="order_id" type="checkbox" value="1">
<input id="n4" name="order_id" type="checkbox" checked="checked" value="2">
<img id="n5" alt="CodePlayer" src="/image/blank.gif" >
<img id="n6" alt="站点logo" title="专注于编程开发技术分享" src="http://static/image/site-url.png" >
</div>
<ul id="n7">
<li id="n8" uid="21">item1</li>
<li id="n9" uid="23">item2</li>
<li id="n10" uid="35">item3</li>
</ul>

我们编写如下jQuery代码:

var $n2 = $("#n2");
// prop()操作针对的是元素(Element对象)的属性,而不是元素节点(HTML文档)的属性
document.writeln( $n2.prop("data-key") ); // undefined
document.writeln( $n2.attr("data-key") ); // UUID
document.writeln( $n2.prop("data_value") ); // undefined
document.writeln( $n2.attr("data_value") ); // 1235456465
// 获取n2的myAttr属性的值,没有该属性,返回undefined
document.writeln( $n2.attr("myAttr") ); //undefined

//设置n5(img元素)的src属性值
$("#n5").attr("src", "http://localhost/static/image/site-name.png");

//只返回第一个匹配元素的uid属性的值
document.writeln( $("li").attr("uid") ); // 21

// 以对象形式同时设置所有img元素的多个属性值
$("img").attr( { height: 180, width: 180, "class": "img-box" } );
document.writeln( $("#n5").attr("height") ); // 180
// 设置所有img元素的title属性值:
// 1.如果该元素已经有了title属性,则不作改变
// 2.如果该元素之前没有title属性,则设置title属性等于它的alt属性
$("img").attr("title", function(index, attrValue){
// 这里的this表示当前DOM元素
return attrValue== undefined ? this.alt : attrValue;
});

document.writeln( $n2.prop("id") ); // n2
document.writeln( $n2.prop("tagName") ); // P
document.writeln( $n2.prop("className") ); // demo test
document.writeln( $n2.prop("innerHTML") ); // CodePlayer
document.writeln( typeof $n2.prop("getAttribute") ); // function

// prop()设置的属性也是针对元素(Element对象),因此也可以通过元素本身直接访问
$n2.prop("prop_a", "CodePlayer");
document.writeln( $n2[0].prop_a ); // CodePlayer
var n2 = document.getElementById("n2");
document.writeln( n2.prop_a ); // CodePlayer

// 以对象形式同时设置多个属性,属性值可以是对象、数组等任意类型
$n2.prop( {
prop_b: "baike",
prop_c: 18,
site: { name: "CodePlayer", url: "http://www.365mini.com/" }
} );
document.writeln( $n2[0].prop_c ); // 18
document.writeln( $n2[0].site.url ); // http://www.365mini.com/ 
// 反选所有的复选框(没选中的改为选中,选中的改为取消选中)
$("input:checkbox").prop("checked", function(index, oldValue){
return !oldValue;
});


三、attr()与prop()之间的区别

在jQuery中,attr()函数prop()函数都用于设置或获取指定的属性,它们的参数和用法也几乎完全相同。

但不得不说的是,这两个函数的用处却并不相同。下面我们来详细介绍这两个函数之间的区别。

0、总览:

从jQuery1.6开始,使用
attr()
获取这些属性的返回值为String类型,如果被选中(或禁用)就返回checked、selected或disabled,否则(即元素节点没有该属性)返回
undefined


jQuery认为:attribute的checked、selected、disabled就是表示该属性初始状态的值,property的
checked
selected
disabled
才表示该属性实时状态的值(值为
true
false
)。


1、操作对象不同

很明显,attr和prop分别是单词attribute和property的缩写,并且它们均表示"属性"的意思。

不过,在jQuery中,attribute和property却是两个不同的概念。attribute表示HTML文档节点的属性,property表示JS对象的属性。
<!-- 这里的id、class、data_id均是该元素文档节点的attribute -->
<div id="message" class="test" data_id="123"></div>

<script type="text/javascript">
// 这里的name、age、url均是obj的property
var obj = { name: "CodePlayer", age: 18, url: "http://www.365mini.com/" };
</script>


在jQuery中,
prop() 函数的设计目标是,用于设置或获取指定DOM元素(指的是JS对象,Element类型)上的属性(property);

attr() 函数的设计目标是,用于设置或获取指定DOM元素所对应的文档节点上(指HTML的元素,元素节点)的属性(attribute)。
<!-- attr()函数针对的是该文档节点的attribute -->
<div id="message" class="test" data_id="123"></div>

<script type="text/javascript">

// prop()函数针对的是该DOM元素(msg)自身的property
var msg = document.getElementById("message");
var $msg = $(msg);

</script>


当然,在jQuery的底层实现中,函数attr()和prop()的功能都是通过JS原生的Element对象

(如上述代码中的msg)实现的。

attr() 函数主要依赖的是Element对象的getAttribute()和setAttribute()两个方法。

prop() 函数主要依赖的则是JS中原生的对象属性获取和设置方式。
<div id="message" class="test" data_id="123"></div>
<script type="text/javascript">
var msg = document.getElementById("message");
var $msg = $(msg);

/* *** attr()依赖的是Element对象的element.getAttribute( attribute ) 和 element.setAttribute( attribute, value ) *** */

// 相当于 msg.setAttribute("data_id", 145);
$msg.attr("data_id", 145);

// 相当于 msg.getAttribute("data_id");
var dataId = $msg.attr("data_id"); // 145

/* *** prop()依赖的是JS原生的 element[property] 和 element[property] = value; *** */

// 相当于 msg["pid"] = "pid值";
$msg.prop("pid", "pid值");

// 相当于 msg["pid"];
var testProp = $msg.prop("pid"); // pid值
</script>


当然,jQuery对这些操作方式进行了封装,使我们操作起来更加方便(比如以对象形式同时设置多个属性),并且实现了跨浏览器兼容。

此外,虽然
prop()
针对的是DOM元素的property,而不是元素节点的attribute。

不过DOM元素某些属性的更改也会影响到元素节点上对应的属性。例如,property的
id
对应attribute的id,property的
className
对应attribute的class。
<div id="message" class="test" data_id="123"></div>
<script type="text/javascript">
var msg = document.getElementById("message");
var $msg = $(msg);

document.writeln( $msg.attr("class") ); // test
$msg.prop("className", "newTest");
// 修改className(property)导致class(attitude)也随之更改
document.writeln( $msg.attr("class") ); // newTest
</script>


2、应用版本不同


attr()
jQuery 1.0版本就有的函数,
prop()
jQuery
1.6
版本新增的函数。毫无疑问,在1.6之前,你只能使用
attr()
函数;1.6及以后版本,你可以根据实际需要选择对应的函数。


3、用于设置的属性值类型不同

由于
attr()
函数操作的是文档节点的属性,因此设置的属性值只能是字符串类型如果不是字符串类型,也会调用其toString()方法,将其转为字符串类型。

prop()
函数操作的是JS对象的属性,因此设置的属性值可以为包括数组和对象在内的任意类型。


4、其他细节问题

在jQuery 1.6之前,只有
attr()
函数可用,该函数不仅承担了attribute的设置和获取工作,还同时承担了property的设置和获取工作。例如:在jQuery
1.6之前,
attr()
也可以设置或获取tagName、className、nodeName、nodeType等DOM元素的property。

直到jQuery 1.6新增
prop()
函数,并用来承担property的设置或获取工作之后,
attr()
才只用来负责attribute的设置和获取工作。

注意(重点):

此外,对于表单元素的checked、selected、disabled等属性,在jQuery
1.6之前,
attr()
获取这些属性的返回值为Boolean类型:如果被选中(或禁用)就返回
true
,否则返回
false


但是从1.6开始,使用
attr()
获取这些属性的返回值为String类型,如果被选中(或禁用)就返回checked、selected或disabled,否则(即元素节点没有该属性)返回
undefined
。并且,在某些版本中,这些属性值表示文档加载时的初始状态值,即使之后更改了这些元素的选中(或禁用)状态,对应的属性值也不会发生改变。

<input id="check1" type="checkbox"checked="checked">

因为jQuery认为:attribute的checked、selected、disabled就是表示该属性初始状态的值,property的
checked
selected
disabled
才表示该属性实时状态的值(值为
true
false
)。

四、总结:

因此,在jQuery 1.6及以后版本中,请使用
prop()
函数来设置或获取
checked
selected
disabled
等属性。对于其它能够用
prop()
实现的操作,也尽量使用
prop()
函数


attr() 获取的是初始状态的值,即使取消了选中,也不会改变。

prop() 获取的值已经发生变化,是实时状态的值。

<input id="uid" type="checkbox" checked="checked" value="1">

<script type="text/javascript">
// 当前jQuery版本为1.11.1
var uid = document.getElementById("uid");
var $uid = $(uid);

document.writeln( $uid.attr("checked") ); // checked
document.writeln( $uid.prop("checked") ); // true

// 取消复选框uid的选中(将其设为false即可)
// 相当于 uid.checked = false;
$uid.prop("checked", false);

// attr()获取的是初始状态的值,即使取消了选中,也不会改变
document.writeln( $uid.attr("checked") ); // checked
// prop()获取的值已经发生变化
document.writeln( $uid.prop("checked") ); // false
</script>


不过如果上面的$uid.prop("checked",false);如果改为:$uid.attr("checked",false);呢?结果会是怎样?

补充:

另外,常用的Attribute,例如id、class、title等,已经被作为Property附加到DOM对象上,可以和Property一样取值和赋值。但是自定义的Attribute,就不会有这样的特殊优待,例如:

<div id="div1" class="divClass" title="divTitle" title1="divTitle1">100</div>


这个div里面的“title1”就不会变成Property。

补充:删除移除相关属性:

JQuery的removeProp()与removeAttr()移除属性的区别 

http://blog.csdn.net/chenchunlin526/article/details/77435722

attr()与prop()函数的详细资料也可参考:
jQuery.prop() 函数详解http://www.365mini.com/page/jquery-prop.htm
jQuery.attr() 函数详解  http://www.365mini.com/page/jquery-attr.htm
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: