js中this.index使用

上面圈出的那句没有执行,因为this.index 是undefined,(也不能直接使用i取代this.index,原因是i不是变化的值,使用alert打印输出的i值始终为3)

解决方式:在for语句执行时给当前lis[i]设置index值;

另一种写法是: 其中将i作为函数参数传入,此时的i是变化的;

 

 例子:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>
window.onload=function(){
var aBtn = document.getElementsByTagName('input');
for(var i=0;i<aBtn.length;i++){
aBtn[i].index=i;
aBtn[i].onclick=function(){
alert('i:'+i); //结果永远为3
alert('this.index:'+this.index); //结果:0,1,2
};
}
};
</script>
</head>
<body>
<input type="button" value="btn1" />
<input type="button" value="btn2" />
<input type="button" value="btn3" />
</body>
</html>

原文地址:https://www.cnblogs.com/hfeng007/p/9299166.html