前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JavaScript基础学习--05自定义属性、索引值

JavaScript基础学习--05自定义属性、索引值

作者头像
用户1148399
发布2018-01-09 15:17:26
7900
发布2018-01-09 15:17:26
举报
文章被收录于专栏:web前端web前端

一、自定义属性

     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>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-08-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档