1. 程式人生 > >js 自定義屬性

js 自定義屬性

getattr 並且 mov spa 程序 自定義屬性的值 數據 循環 sco

html標簽中有沒有什麽自帶的屬性可以存儲成績的----沒有 本身html標簽沒有這個屬性,自己(程序員)添加的,----自定義屬性---為了存儲一些數據 在html標簽中添加的自定義屬性,如果想要獲取這個屬性的值,需要使用getAttribute("自定義屬性的名字")才能獲取這個屬性的值 使用方法:   設置自定義屬性:setAttribute("屬性的名字","屬性的值");   獲取自定義屬性的值:getAttribute("屬性的名字")
<ul id="uu">
  <li score="10">小明的數學成績</li>
  <li score="
20">小紅的數學成績</li> <li score="30">小綠的數學成績</li> <li score="40">小黃的數學成績</li> <li score="50">小琴的數學成績</li> </ul>
//根據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對象上,不在標簽中 //用setAttribute去設置自定義屬性的值 list[i].setAttribute("score",(i+1)*10); //點擊每個li標簽,顯示對應的自定義屬性值 list[i].onclick=function(){ //getAttribute獲取每個對應的自定義屬性的值 alert(this.getAttribute("score")); }; }
移除自定義屬性:removeAttribute("屬性的名字")
//
點擊按鈕移除元素的自定義屬性 document.getElementById("btn").onclick=function () { //my$("dv").removeAttribute("score"); //移除元素的類樣式 //值沒有了,但是屬性還是有的 //my$("dv").className=""; //也可以移除元素的自帶的屬性 document.getElementById("btn").removeAttribute("class"); };

js 自定義屬性