Demos: ??https://github.com/jiangheyan/JavaScriptBase?
?
一、自定義屬性1、讀寫操作
<input abc="123" type="button" value="按鈕" /> ========================================================= //讀寫: var aBtn = document.getElementsByTagName('input'); aBtn[0].abc = '456';
2、js可以為任何HTML元素添加任意個自定義屬性
3、自定義屬性可以作為判斷的依據,相對于用class后者flag變量判斷,優點:
3.1 ? ? 有時候不允許操作class時,可以利用自定義屬性,通過判斷自定義屬性的值,從而操作流程
3.2 ? ? 一個flag變量只能判斷一組對象,當對象在循環中有多組對象時,只能用class 或者 自定義屬性
4、for循環里面的i
1 for(var i = 0; i < aLi.length; i++) { 2 i //這里的 i 是0、1、2…… 3 aLi[i].onclick = function() { 4 i //這里的 i 涉及到閉包和作用域問題,不能返回1、2、…… 只能返回aLi.length 5 } 6 }
5、自定義索引
1 for(var i = 0; i < aLi.length; i++) { 2 aLi[i].index = i; //給每個li添加自定義屬性index,值為i,模擬成為索引 3 aLi[i].onclick = function() { 4 i //這里的 i 涉及到閉包和作用域問題,不能返回1、2、…… 只能返回aLi.length 5 } 6 }
5.1 ? ? 自定義索引的應用
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 5 <title>無標題文檔</title> 6 <script> 7 window.onload = function (){ 8 var aBtn = document.getElementsByTagName('input'); 9 var aP = document.getElementsByTagName('p'); 10 11 // 想建立“匹配”“對應”關系,就用索引值 12 var arr = [ '莫濤', '張森', '杜鵬' ]; 13 14 for( var i=0; i<aBtn.length; i++ ){ 15 16 aBtn[i].index = i; // 自定義屬性(索引值) 17 18 aBtn[i].onclick = function (){ 19 // alert( arr[ this.index ] ); 20 this.value = arr[ this.index ]; 21 22 aP[ this.index ].innerHTML = arr[ this.index ]; 23 }; 24 } 25 }; 26 </script> 27 </head> 28 29 <body> 30 31 <input type="button" value="btn1" /> 32 <input type="button" value="btn2" /> 33 <input type="button" value="btn3" /> 34 <p>a</p> 35 <p>b</p> 36 <p>c</p> 37 38 </body> 39 </html>
?