jQuery的属性操作, 是对html文档中的属性进行读取、设置和移除操作。比如,attr()、 removeAttr()。
1. attr()
attr()可以设置属性值或者返回被选元素的属性值
1.1 使用attr()获取值
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>attr()获取值</title> 6 <script type="text/javascript" src="jquery.js"></script> 7 <script> 8 9 $(function () { 10 var cla = $("div").attr("class"); 11 console.log(cla); 12 var id = $("div").attr("id"); 13 console.log(id); 14 }) 15 16 </script> 17 </head> 18 <body> 19 <div class="divClass" id="divId"></div> 20 </body> 21 </html>
结果为:
1.2 使用attr()设置值
1.2.1 使用attr()设置一个值
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>attr() Demo</title> <script type="text/javascript" src="jquery.js"></script> <script> $(function () { $("div").attr("class", "box"); }) </script> </head> <body> <div></div> <div></div> </body> </html>
结果显示为:
1.2.2 使用attr()设置多个值
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>attr() Demo</title> <script type="text/javascript" src="jquery.js"></script> <script> $(function () { $("div").attr({ "class": "divClass", "id": "divId" }); }) </script> </head> <body> <div></div> </body> </html>
设置效果为:
2. removeAttr()
移除属性
2.1 删除单个属性
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>removeAttr() Demo</title> <script type="text/javascript" src="jquery.js"></script> <script> $(function () { $("div").removeAttr("class"); $("div").removeAttr("id"); }) </script> </head> <body> <div class="divClass" id="divId"></div> </body> </html>
设置效果为:
2.2 removeAttr()设置多个属性值
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>removeAttr() Demo</title> 6 <script type="text/javascript" src="jquery.js"></script> 7 <script> 8 $(function () { 9 $("div").removeAttr("class id"); 10 }) 11 </script> 12 </head> 13 <body> 14 <div class="divClass" id="divId"></div> 15 </body> 16 </html>
显示结果为: