- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>JS基础——索引值的应用</title>
- <script>
- window.onload = function(){
- var aBtn = document.getElementsByTagName('input');
- var arr = ['张三','李四','王五'];
- for(var i=0; i<aBtn.length; i++){
- aBtn[i].index = i;
- aBtn[i].onclick = function(){
- //alert(this.index);
- this.value = arr[this.index];
- };
- }
- };
- </script>
- </head>
- <body>
- <!--input[value="按钮"]*3-->
- <input type="button" value="按钮">
- <input type="button" value="按钮">
- <input type="button" value="按钮">
- </body>
- </html>
思路:
首先获取相关元素,然后通过for循环出所有的按钮,然后给每个按钮添加一个自定义索引值,当点击按钮时,可以alert一下当前被点击按钮的索引值是多少(测试),
接着当点击按钮是,通过数组的索引值赋值给当前点击的按钮的value上。