1. 程式人生 > >獲取for迴圈中的索引值

獲取for迴圈中的索引值

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
li{
margin-bottom: 10px;
}
</style>
</head>
<body>
<ul>
<li style="width:100%;height:30px;background:#f99;">1</li>
<li style="width:100%;height:30px;background:#9f9;">2</li>
<li style="width:100%;height:30px;background:#9ff;">3</li>
</ul>
<script>
//獲取索引值的方法
//1.用index
var oList = document.getElementsByTagName("li");

for(var i=0;i<oList.length;i++){
oList[i].index = i;
oList[i].onclick = function(){
var index = this.index;
console.log(index);
}
}
//2.用到閉包
for(var i=0;i<oList.length;i++){
(function(index){  //index相當於形參
oList[index].onclick = function(){
console.log(index);
}
})(i) //i相當於實參
}
</script>
</body>
</html>