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)
};