【问题标题】:addEventListener JavaScript [duplicate]addEventListener JavaScript [重复]
【发布时间】:2017-08-16 03:00:03
【问题描述】:

我正在学习 JavaScript 上的 addEventListener,当我输入这段代码时:

test();
function test(){
    var td = document.getElementsByTagName("td");
    td.addEventListener('mouseenter', function(){
        td.style.background = "green";
    });
}

它没有工作。谁能解释一下为什么?

【问题讨论】:

  • .getElementsByTagName() 返回一个列表。该列表没有.addEventListener() 方法。列表中的各个元素都有一个 .addEventListener() 方法,因此您需要遍历列表(如链接的副本中一样)。
  • Document.getElementsByTagName 返回一个节点列表,如果你想应用 addEventListener 你需要使用 Array.prototype.slice.apply 到 documet.getElementsByTagName,然后使用 for 或 forEach 函数来应用 addEventListener到数组中的每个 td 元素

标签: javascript dom-events


【解决方案1】:

getElementsByTagName 返回一个 HTMLcollection,因此您需要传递要在其上添加事件的元素的索引,或者循环遍历集合以将事件添加到每个元素

function test(){
    // selecting only first element from the collection
    var td = document.getElementsByTagName("td")[0];
    td.addEventListener('mouseenter', function(){
        td.style.background = "green";
    });
}

test();

将 addListener 添加到集合中的所有元素

function test(){
var cells = table.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
cells[i].addEventListener('mouseenter', function(){
            this.style.background = "green";
        });

}};
test()

【讨论】:

    猜你喜欢
    • 2017-02-04
    • 2022-12-05
    • 1970-01-01
    • 2021-01-27
    • 2012-12-17
    • 2011-10-24
    • 2023-03-14
    • 2021-12-14
    • 2011-01-23
    相关资源
    最近更新 更多