juqery筆記 jquery操縱DOM元素屬性 attr()

來源:互聯網
上載者:User

標籤:

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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.