添加自定义属性值及应用

添加自定义属性值:

 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     
10     for( var i=0; i<aBtn.length; i++ ){
11         
12         aBtn[i].index = i;            // 自定义属性(索引值)
13         //aBtn[0].index = 0;            // for第一遍循环时:i=0; 相当于给第一个input自定义一个属性 index=0;
14         //aBtn[1].index = 1;            // for第二遍循环时:i=1; 相当于给第二个input自定义一个属性 index=1;
15         //aBtn[2].index = 2;            // for第三遍循环时:i=2; 相当于给第三个input自定义一个属性 index=2;
16         
17         //此时,i已经循环了3遍 i=3;
18         aBtn[i].onclick = function (){
19             
20             // alert( i );            // 3
21             alert( this.index );
22         
23         };
24     }
25 };
26 </script>
27 </head>
28 
29 <body>
30 
31 <input index=0 type="button" value="btn1" />
32 <input index=1 type="button" value="btn2" />
33 <input index=2 type="button" value="btn3" />
34 
35 </body>
36 </html>

添加自定义属性值实例讲解:

 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 = [ 'HTML', 'JAVASCRIPT', 'CSS' ];
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>
原文地址:https://www.cnblogs.com/trtst/p/3753945.html