JS基础——索引值的应用

来源:互联网 发布:已备案过期删除域名 编辑:程序博客网 时间:2024/06/03 17:38


[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <!doctype html>  
  2. <html>  
  3. <head>  
  4. <meta charset="utf-8">  
  5. <title>JS基础——索引值的应用</title>  
  6. <script>  
  7. window.onload = function(){  
  8.     var aBtn = document.getElementsByTagName('input');  
  9.     var arr = ['张三','李四','王五'];  
  10.       
  11.     for(var i=0; i<aBtn.length; i++){  
  12.         aBtn[i].index = i;  
  13.         aBtn[i].onclick = function(){  
  14.             //alert(this.index);  
  15.             this.value = arr[this.index];     
  16.         };    
  17.     }     
  18. };  
  19. </script>  
  20. </head>  
  21.   
  22. <body>  
  23. <!--input[value="按钮"]*3-->  
  24. <input type="button" value="按钮">  
  25. <input type="button" value="按钮">  
  26. <input type="button" value="按钮">  
  27. </body>  
  28. </html>  

思路:

首先获取相关元素,然后通过for循环出所有的按钮,然后给每个按钮添加一个自定义索引值,当点击按钮时,可以alert一下当前被点击按钮的索引值是多少(测试),

接着当点击按钮是,通过数组的索引值赋值给当前点击的按钮的value上。

0 0
原创粉丝点击