1. 程式人生 > >jQuery中的attr()與prop()設定屬性、獲取屬性的區別

jQuery中的attr()與prop()設定屬性、獲取屬性的區別

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頁)
總結建議: 獲取和設定disabledselectedchecked這些屬性時,應該使用
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()方法代替。

注意:不要使用該方法來移除諸如 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型別,如果被選中(或禁用)就返回checkedselecteddisabled,否則(即元素節點沒有該屬性)返回undefined
jQuery認為:attributecheckedselecteddisabled就是表示該屬性初始狀態的值,propertycheckedselecteddisabled才表示該屬性實時狀態的值(值為truefalse)。

1、操作物件不同

很明顯,attrprop分別是單詞attributeproperty的縮寫,並且它們均表示"屬性"的意思。

不過,在jQuery中,attributeproperty卻是兩個不同的概念。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()函式操作的是文件節點的屬性,因此設定的屬性值只能是字串型別如果不是字串型別,也會呼叫其

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的設定和獲取工作。

注意(重點):

此外,對於表單元素的checkedselecteddisabled等屬性,在jQuery 1.6之前attr()獲取這些屬性的返回值為Boolean型別:如果被選中(或禁用)就返回true,否則返回false

但是從1.6開始,使用attr()獲取這些屬性的返回值為String型別,如果被選中(或禁用)就返回checkedselecteddisabled,否則(即元素節點沒有該屬性)返回undefined。並且,在某些版本中,這些屬性值表示文件載入時的初始狀態值,即使之後更改了這些元素的選中(或禁用)狀態,對應的屬性值也不會發生改變。

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

因為jQuery認為:attributecheckedselecteddisabled就是表示該屬性初始狀態的值,propertycheckedselecteddisabled才表示該屬性實時狀態的值(值為truefalse)。

四、總結:

因此,在jQuery 1.6及以後版本中,請使用prop()函式來設定或獲取checkedselecteddisabled等屬性。對於其它能夠用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()移除屬性的區別