实现一段脚本,使得点击对应链接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>
PHPz2017-04-10 15:04:10
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>
这样?
PHPz2017-04-10 15:04:10
方法一:
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);
}
}