萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> JQuery中attr方法和removeAttr方法用法實例

JQuery中attr方法和removeAttr方法用法實例

   本文實例講述了JQuery中attr方法和removeAttr方法用法。分享給大家供大家參考。具體如下:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> div{width:100px;margin:0px auto;border:1px solid red;} </style> <script src="jquery-1.6.2.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#btnChange").click(function () { var $divs = $("div"); //----1.舉例1 //$divs.eq(0).attr("MyAttr", "Ronaldo"); //eq返回指定下標的JQuery對象(注意:此時$divs中有兩個div的dom元素) //$divs.eq(1).attr("MyAttr", "Ronaldo1"); //alert($divs.attr("MyAttr")); //讀取MyAttr屬性,注意,只會讀取出第一個元素的該屬性 //----2.舉例2 使用JSon格式設置attr //$divs.eq(0).attr({ "MyAttr": "Ronaldo", "Age": "19" }); //$divs.eq(1).attr({ "MyAttr": "Rivaldo", "Age": "29" }); //alert("MyAttr:" + $divs.eq(1).attr("MyAttr") + ",Age:" + $divs.eq(1).attr("Age")); //----3.舉例3 移除屬性 $divs.eq(0).attr({ "MyAttr": "Ronaldo", "Age": "19" }); $divs.eq(1).attr({ "MyAttr": "Rivaldo", "Age": "29" }); alert("MyAttr:" + $divs.eq(1).attr("MyAttr") + ",Age:" + $divs.eq(1).attr("Age")); $divs.eq(1).removeAttr("Age"); alert("MyAttr:" + $divs.eq(1).attr("MyAttr") + ",Age:" + $divs.eq(1).attr("Age")); }); }); </script> </head> <body> <input id="btnChange" type="button" value="Click Me" /> <div id="div1">我是div1</div> <div id="div2">我是div2</div> </body> </html>

  希望本文所述對大家的jQuery程序設計有所幫助。

copyright © 萬盛學電腦網 all rights reserved