我想将mouseover
事件添加到带有JS的linkLink
类的每个链接。
控制台出错 - Cannot read property style of undefined
。
每当我设置索引时,请设置为 - l[0].addEventListener(...)
工作正常,但不是变量i
。有帮助吗?
var l = document.getElementsByClassName('linkLink');
for (var i = 0; i < l.length; i++) {
l[i].addEventListener("mouseover", function() { l[i].style.backgroundColor = "black"; });
if ((i % 2) === 0) l[i].style.color = "crimson";
else l[i].style.color = "gold";
}
<a class="linkLink" href="#">link I</a><br>
<a class="linkLink" href="#">link II</a><br>
<a class="linkLink" href="#">link III</a><br>
答案 0 :(得分:0)
在处理函数中使用this
代替li[i]
。
var l = document.getElementsByClassName('linkLink');
for (var i = 0; i < l.length; i++) {
l[i].addEventListener("mouseover", function() { this.style.backgroundColor = "black"; });
//return back to original background color on mouseleave.
l[i].addEventListener("mouseleave", function() { this.style.backgroundColor = "white"; });
if ((i % 2) === 0) l[i].style.color = "crimson";
else l[i].style.color = "gold";
};
<a class="linkLink" href="#">link I</a><br>
<a class="linkLink" href="#">link II</a><br>
<a class="linkLink" href="#">link III</a><br>