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)
};
2.使用ES6的let
var liList = document.getElementsByTagName('li')
for (let i = 0; i < liList.length; i++) {
liList[i].onclick = function(){
console.log(i)
}
};
3.forEach实现
var liList = document.getElementsByTagName('li')
var liArr = [].slice.call(liList)//将liList这个类数组转化成数组,forEach只能遍历数组
liArr.forEach(function(ele,i){
ele.onclick = function(){ console.log(i