1.html的基本结构:
- 1
- 2
- 3
- 4
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)
};