html:
<ul>
<li>ili>
<li>ili>
<li>ili>
<li>ili>
ul>
使用var:
var elements = document.getElementsByTagName('li');
for (var i = 0; i < elements.length; i++) {
elements[i].onclick = function () {
console.log(i);
alert(i);
};
}
结果:
点击任意li标签控制台都打印 4
使用let:
var elements = document.getElementsByTagName('li');
for (let i = 0; i < elements.length; i++) {
elements[i].onclick = function () {
console.log(i);
alert(i);
};
}
点击对应li标签控制台打印对应id
解释: