JavaScript可以为任何HTML元素添加任意的自定义属性,而且你可能无意中已经使用过自定义属性了,那么自定义属性通常有哪些应用呢?
1、想用“匹配”、对应关系的时候就用索引值
2、同时控制多组元素
3、开关切换,多组元素开关的切换
就总结到这里,下面来看看几个例子吧
JavaScript自定义属性索引值:
HTML
<input type="button" value="btn1">
<input type="button" value="btn2">
<input type="button" value="btn3">
JavaScript:
var aInp=document.getElementsByTagName(‘input‘); ???for (var i = 0; i < aInp.length; i++) { ???????aInp[i].index=i;//自定义属性,就是通常用的索引值 ???????aInp[i].onclick=function(){ ???????????alert(this.index);//弹出当前点击的是第几个按钮,从0开始 ???????} ???};
同时控制多组元素:
HTML:<input type="button" value="0">
<input type="button" value="0">
<input type="button" value="0">
JavaScript:
var aInp=document.getElementsByTagName(‘input‘); ???var arr=[‘A‘,‘B‘,‘C‘,‘D‘,‘E‘,‘F‘,‘G‘]; ???for (var i = 0; i < aInp.length; i++) { ???????aInp[i].num=0;//自定义属性 ???????aInp[i].onclick=function(){ ???????????this.value=arr[this.num]; ???????????this.num++; ???????????if (this.num===arr.length) { ???????????????this.num=0; ???????????}; ???????} ???};
自定义属性组开关:
CSS:.cont{
???????width: 400px; ???????margin: 30px auto; ???????position: relative; ???} ???.cont input{ ???????height: 100px; ???????width: 100px; ???????background: #ddd; ???????margin-left: 20px; ???????font-size: 30px; ???????border:1px solid #ccc; ???} ???.cont .active{ ???????background: #ffc7d2; ???????color: #fff; ???????border:1px solid #fc6d88; ???}
HTML:
<div class="cont"> ???<input type="button" value="btn1"> ???<input type="button" value="btn2"> ???<input type="button" value="btn3"></div>
JavaScript:
var aInp=document.getElementsByTagName(‘input‘);
for (var i = 0; i < aInp.length; i++) { ???????aInp[i].Onoff=true;//自定义属性,切换开关 ???????aInp[i].onclick=function(){ ???????????if (this.Onoff) { ???????????????this.className=‘active‘; ???????????????this.Onoff=false; ???????????} ???????????else{ ???????????????this.className=‘‘; ???????????????this.Onoff=true; ???????????}; ???????} ???};
JS自定义属性的运用
原文地址:http://www.cnblogs.com/suntao12138/p/7622750.html