我在将索引传递给 for 循环中的 eventlistener 时遇到了一点问题。
for (var i = 0; i < todos.length; i++) {
console.log("XD");
todos[i].addEventListener("mouseover", function() {
trashShow[i].style.display = "inline";
});
}
通信显示“无法读取未定义的属性‘style’”。我认为索引是错误的,所以数组中没有这个元素。 感谢您的帮助。
最佳答案
i have a little problem with passing the index to eventlistener in for loop.
如果您使用 let
声明迭代器变量 i
,而不是使用 var
,您将看到循环递增 i
每次在事件监听器中都正确,并且永远不会返回 undefined
错误。
工作示例:
var sections = document.getElementsByTagName('section');
var section1Divs = sections[0].getElementsByTagName('div');
var section2Divs = sections[1].getElementsByTagName('div');
for (let i = 0; i < section1Divs.length; i++) {
section1Divs[i].addEventListener('mouseover', function() {
section2Divs[i].style.backgroundColor = 'rgb(255, 0, 0)';
});
section1Divs[i].addEventListener('mouseout', function() {
section2Divs[i].style.backgroundColor = 'rgb(191, 191, 191)';
});
}
div {
display: inline-block;
width: 50px;
height: 50px;
margin-right: 12px;
background-color: rgb(191, 191, 191);
}
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
进一步阅读:
What's the difference between using "let" and "var" to declare a variable in JavaScript?
关于javascript - 如何将索引传递给for中的addeventlistener? JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50315246/