实现一段javascript脚本,使得点击对应链接alert出相应的编号
PHP中文网
PHP中文网 2017-04-10 15:02:10
0
2
417

实现一段脚本,使得点击对应链接alert出相应的编号,比如点击第一个链接就alert 1。

html<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
  <a href='#'> 第一个链接 </a> </br>
  <a href='#'> 第二个链接 </a> </br>
  <a href='#'> 第三个链接 </a> </br>
  <a href='#'> 第四个链接 </a> </br>
</body>
PHP中文网
PHP中文网

认证0级讲师

reply all(2)
PHPzhong
html<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
  <a href='#'> 第一个链接 </a> </br>
  <a href='#'> 第二个链接 </a> </br>
  <a href='#'> 第三个链接 </a> </br>
  <a href='#'> 第四个链接 </a> </br>
  <script type="text/javascript">
    var lis = document.links;
    for(var i = 0, length = lis.length; i < length; i++) {
      (function(i) {
        lis[i].onclick = function() {
          alert(i + 1);
        };
      })(i);
    }
  </script>
</body>

这样?

PHPzhong

方法一:

var a=document.getElementsByTagName("a");
Array.prototype.forEach.call(a,function(el,index){
    el.onclick=function(){
         alert(index+1);
    }
})

方法二:

var a=document.getElementsByTagName("a");
for(var i=0;i<a.length;i++){
    var el=a[i];
    el.index=i+1;
    el.onclick=function(){
        alert(this.index);
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template