標籤:
jQuery操縱元素屬性方法:
attr():讀或者寫匹配元素的屬性值。
removeAttr():從匹配的元素中溢出指定的屬性。
attr()方法 讀操作
attr()讀操作,讀取的是匹配元素中第一個元素的指定屬性值。
格式:.attr(attributeName),傳回值類型:String,讀取不存在的屬性會返回undefined。
注意選取器的選擇結果可能是一個集合,這裡僅僅擷取的是集合中第一個元素的該屬性值。
例子:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script type="text/javascript" src="/jquery/jquery.js"></script> 5 <script type="text/javascript"> 6 $(document).ready(function () { 7 $("button").click(function () { 8 alert($("p").attr("title"));//擷取屬性 9 // this code can only get the first element‘s attribute.10 });11 });12 </script>13 </head>14 <body>15 <p title="title1">paragraph 1</p>16 <p title="title2">paragraph 2</p>17 <br/>18 <button>get title</button>19 </body>20 </html>
運行結果:彈框顯示: title1.
想要分別擷取每一個元素的屬性,需要使用jQuery的迴圈結構,比如.each()或.map()方法. 上面的例子可以改成:
<script type="text/javascript"> $(document).ready(function (){ $("button").click(function(){ //get attribute for every element in selection. $("p").each(function () { alert($(this).attr("title")); }); }); }); </script>
即可分別擷取每個元素的屬性.
attr()方法 寫操作
attr()寫操作,為匹配元素的一個或多個屬性賦值。
一般格式:.attr(attributeName,value),紀委屬性設定value。
傳回值類型:jQuery,也即支援鏈式方法調用。
執行操作的時候,如果指定的屬性名稱不存在,將會增加一個改名字的屬性,即增加自訂屬性,
起名為屬性名稱,其值為value值。
寫屬性是為匹配集合中的每一個元素都進行操作的,例子:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script type="text/javascript" src="/jquery/jquery.js"></script> 5 <script type="text/javascript"> 6 $(document).ready(function(){ 7 $("#button1").click(function(){ 8 $("p").attr("title","Hello World"); 9 10 });11 });12 </script>13 </head>14 <body>15 <input type="button" id="button1" value="button1"></input>16 <p>This is a paragraph.</p>17 <div>This is a div.</div>18 <p>This is another paragraph.</p>19 <div>This is another div.</div>20 </body>21 </html>
點擊按鈕之後所有的p都加上了title="Hello World”的屬性。
juqery筆記 jquery操縱DOM元素屬性 attr()