1.html的基本结构:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
复制代码
2.js实现部分
1.使用立即执行函数 var liList = document.getElementsByTagName('li')
for (var i = 0; i < liList.length; i++) {
(function(i){
liList[i].onclick = function(){
console.log(i)
}
})(i)
};
var liList = document.getElementsByTagName('li')
for (let i = 0; i < liList.length; i++) {
liList[i].onclick = function(){
console.log(i)
}
};
var liList = document.getElementsByTagName('li')
var liArr = [].slice.call(liList)//将liList这个类数组转化成数组,forEach只能遍历数组
liArr.forEach(function(ele,i){
ele.onclick = function(){ console.log(i) }
})
var liList = document.getElementsByTagName('li')
function fun(idx){
this.onclick = function(){ console.log(idx) }
}
for (var i = 0; i < liList.length; i++) {
fun.call(liList[i],i)
};