无法将事件侦听器添加到数组元素

时间:2017-12-16 11:58:13

标签: javascript

我想将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>

1 个答案:

答案 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>