僅記錄學習的新知識和示例,無干貨。
1.setAttribute和getAttribute (Attribute:屬性)
setAttribute:為元素添加指定的屬性,並為其賦值;如果指定的屬性已經存在,則僅設置或改變它的值。
調用方法:element.setAttribute(attributeName,attributeValue)
這是一個方法,無返回值,IE8及以下不支持。
getAttribute:返回指定屬性名的屬性值。
調用方法:element.getAttribute(attributeName)
返回值為字符串
總結:attributeName為元素的屬性名,attributeValue為元素的屬性值,二者均為字符型
示例:
1 var comm={ 2 //setAttr為對象comm的一個方法,用於給元素設置屬性 3 //e為形參,代表元素名稱;strName為形參,代表所設置屬性的名稱;strValue為形參,代表所設置屬性的值 4 setAttr:function(e,strName,strValue){ 5 e.setAttribute(strName,strValue); 6 }, 7 //getAttr為對象comm的一個方法,用於獲取元素屬性 8 //e為形參,代表元素名稱;strName為形參,代表所設置屬性的名稱,無值 9 getAttr:function(e,strName){ 10 return e.getAttribute(strName); 11 } 12 }
以上為自定義一個對象用於給元素設置屬性的方法。
調用上訴對象實現元素屬性的改變示例如下:

1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <script type="text/javascript" src=../../js/system.js></script> 6 <title></title> 7 <style type="text/css"> 8 .red{ 9 width: 260px; 10 height: 100px; 11 line-height: 100px; 12 text-align: center; 13 border: solid 1px red; 14 margin: auto; 15 } 16 .blue{ 17 width: 260px; 18 height: 100px; 19 line-height: 100px; 20 text-align: center; 21 border: solid 1px blue; 22 margin: auto; 23 } 24 </style> 25 </head> 26 <body> 27 <div id="a" class="red">hello,Js!</div> 28 <div id="b">hello,Js2!</div> 29 <br/> 30 <input type="button" value="點我變色" id="bitRed"/> 31 <script type="text/javascript"> 32 //定義一個變量clasName,用於保存使用comm.getAttr獲取的ID號為a的元素的class屬性值 33 var clasName =comm.getAttr($$("a"),"class"); 34 //調用comm.serAttr函數為ID號為b的元素設置class屬性,屬性值為clasName,既a的class屬性值 35 comm.setAttr($$("b"),"class",clasName); 36 //設定ID號為bitRed的元素的點擊事件 37 $$("bitRed").onclick=function(){ 38 //為元素設置屬性 39 //console.log()方法用於檢測是否綁定成功,可刪除 40 console.log("123"); 41 //為ID為a的元素設置樣式,括號內實參分別對應形參e,strName,strValue 42 comm.setAttr($$("a"),"class","blue");//屬性名,屬性值 43 //定義一個變量clasName,用於保存使用comm.getAttr獲取的ID號為a的元素的class屬性值 44 //此變量clasName為局部變量,與上一個不同 45 var clasName =comm.getAttr($$("a"),"class"); 46 //調用comm.serAttr函數為ID號為b的元素設置class屬性,屬性值為clasName,既a的class屬性值 47 comm.setAttr($$("b"),"class",clasName); 48 } 49 </script> 50 </body> 51 </html>
此示例的要求是為ID為a的元素設置樣式,ID為b的元素樣式跟隨元素a的樣式,點擊按鈕,元素a的樣式發生改變,同時元素b的樣式隨之改變。
開始定義一個全局變量clasName,並調用comm對象的getAttr方法獲取元素a的屬性,並使用comm對象的setAttr方法為元素b設置屬性,達到開始元素b屬性跟隨元素a的要求。然后再點擊事件中,首先調用comm對象的srtAttr方法為元素a設置新的屬性,並定義局部變量clasName存儲使用comm對象的getAttr方法得到的a的屬性,再給b設置局部變量clasName中存儲的屬性。