The examples in this article describe the usage of attr method and removeAttr method in JQuery. Share it with everyone for your reference. The details are as follows:
<!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>
I hope this article will be helpful to everyone’s jQuery programming.