JavaScript中自定義屬性的操作
阿新 • • 發佈:2018-12-10
目錄
1.getAttribute("自定義屬性的名字") 獲取自定義屬性的值
案例:點選li獲取成績
<head> <meta charset="UTF-8"> <title>Title</title> <style> ul { list-style-type: none; cursor: pointer; } </style> </head> </head> <body> <ul id="uu"> <li score="10">喜羊羊的成績</li> <li score="20">美羊羊的成績</li> <li score="30">懶羊羊的成績</li> <li score="40">沸羊羊的成績</li> <li score="50">暖羊羊的成績</li> </ul> <script> //html標籤中有沒有什麼自帶的屬性可以儲存成績的----沒有 //本身html標籤沒有這個屬性,自己(程式設計師)新增的,----自定義屬性---為了儲存一些資料 //在html標籤中新增的自定義屬性,如果想要獲取這個屬性的值,需要使用getAttribute("自定義屬性的名字")才能獲取這個屬性的值 //獲取所有的li標籤 var list = document.getElementsByTagName("li"); for (var i = 0; i < list.length; i++) { list[i].onclick = function () { //alert(this.score);//不能 alert(this.getAttribute("score")); //可以 }; } </script> </body>
2.setAttribute("屬性的名字","屬性的值"); 設定自定義屬性的值
案例:先設定li的成績,再點選li獲取成績
<head> <meta charset="UTF-8"> <title>Title</title> <style> ul { list-style-type: none; cursor: pointer; } </style> </head> </head> <body> <ul id="uu"> <li>喜羊羊的成績</li> <li>美羊羊的成績</li> <li>懶羊羊的成績</li> <li>沸羊羊的成績</li> <li>暖羊羊的成績</li> </ul> <script> //總結:設定自定義屬性:setAttribute("屬性的名字","屬性的值"); //獲取自定義屬性的值:getAttribute("屬性的名字") //獲取所有的li標籤,然後為每個標籤中動態的新增自定義屬性和值 //點選的時候獲取該標籤的自定義屬性的值 //根據id獲取ul標籤,並且或者該標籤中所有的li var list = document.getElementById("uu").getElementsByTagName("li"); //迴圈遍歷 for (var i = 0; i < list.length; i++) { //先為每個li新增自定義屬性 //list[i].score=(i+1)*10;//此方式,自定義屬性在DOM物件上,不在標籤中 list[i].setAttribute("score", (i + 1) * 10); //點選每個li標籤,顯示對應的自定義屬性值 list[i].onclick = function () { alert(this.getAttribute("score")); }; } </script> </body>
3.removeAttribute("屬性的名字") 移除自定義屬性
list[i].removeAttribute("score"); 移除元素的類樣式 list[i].setAttribute("score", ""); 移除元素的值,樣式還在 也可以移除元素的自帶的屬性
案例:點選按鈕移除元素的自定義屬性
<head> <meta charset="UTF-8"> <title>Title</title> <style> ul { list-style-type: none; cursor: pointer; } </style> </head> <body> <input type="button" value="移除自定義屬性" id="btn"/> <ul id="uu"> <li score="10">喜羊羊的成績</li> <li score="20">美羊羊的成績</li> <li score="30">懶羊羊的成績</li> <li score="40">沸羊羊的成績</li> <li score="50">暖羊羊的成績</li> </ul> <script> //點選按鈕移除元素的自定義屬性 document.getElementById("btn").onclick = function () { //獲取所有的li標籤 var list = document.getElementsByTagName("li"); for (var i = 0; i < list.length; i++) { list[i].removeAttribute("score"); } }; </script> </body>