- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>JS基础——自定义属性2</title>
- <script>
- window.onload = function(){
- var aBtn = document.getElementsByTagName('input');
- var arr = ['孙悟空','琪 琪','孙悟饭','孙悟天'];
- for(var i=0; i<aBtn.length; i++){
- aBtn[i].index =0;
- aBtn[i].onclick = function(){
- //alert(this.index);
- this.value = arr[this.index];
- this.index ++;
- if(this.index == arr.length){
- this.index = 0;
- }
- };
- }
- };
- </script>
- </head>
- <body>
- <input type="button" value="按钮">
- <input type="button" value="按钮">
- <input type="button" value="按钮">
- </body>
- </html>
思路:
先获取元素,然后通过for循环出所有的按钮,再给每个按钮添加一个自定义的索引值(aBtn[i].index = 0;)
当点击按钮时,先alert测试一下当前的索引值(this.index),然后把数组对应的索引值赋给当前点击的按钮,
同时让当前索引值自增,当索引值增加到数组的长度时,就让索引值回到0,即可,这样点击任意按钮都能各自循环
数组中的元素而不会产生冲突。