码迷,mamicode.com
首页 > Web开发 > 详细

js中this.index使用

时间:2018-07-12 14:39:57      阅读:750      评论:0      收藏:0      [点我收藏+]

标签:def   func   执行   text   技术分享   html   elements   oct   http   

 

 

 

 

技术分享图片

上面圈出的那句没有执行,因为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>

 

js中this.index使用

标签:def   func   执行   text   技术分享   html   elements   oct   http   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!