未捕获的TypeError:button.addEventListener不是函数

时间:2018-11-06 01:33:45

标签: javascript html

我正在独自学习js,并且是编程的新手。我停留在下面的代码上,任何帮助将不胜感激:

<div id="container">
  <h1>To-Do list</h1>
  <input type="text">
  <ul>
    <li><span>X</span> one</li>
    <li><span>X</span> two</li>
    <li><span>X</span> three</li>
  </ul>
</div>

JavaScript部分:

let li = document.getElementsByTagName("li");

let button = document.getElementsByTagName("span");

button.addEventListener("click", function() {
  console.log("clicked");
})

这抛出一个错误,表明它不是函数。我的错误在哪里?

3 个答案:

答案 0 :(得分:0)

函数Element.getElementsByTagName()返回元素的HTMLCollection,您需要对其进行循环以绑定事件。

let li = document.getElementsByTagName("li");
let buttons = document.getElementsByTagName("span");

Array.from(buttons).forEach(b => {
  b.addEventListener("click", function() {
    console.log("clicked");
  });
});
<div id="container">
  <h1>To-Do list</h1>
  <input type="text">
  <ul>
    <li><span>X</span> one</li>
    <li><span>X</span> two</li>
    <li><span>X</span> three</li>
  </ul>
</div>

答案 1 :(得分:0)

getElementsByTagName返回元素列表

我们可以在每个元素上添加EventListener

let li = document.getElementsByTagName("li");

let button = document.getElementsByTagName("span");

console.log(button); // list of elements

// and we have to addEventListener on every element
Array.prototype.map.call(button, (b) => {
  b.addEventListener("click", function() {
    console.log("clicked");
  })
})
<div id="container">
  <h1>To-Do list</h1>
  <input type="text">
  <ul>
    <li><span>X</span> one</li>
    <li><span>X</span> two</li>
    <li><span>X</span> three</li>
  </ul>
</div>

或者我们可以addEventListener在父元素上(例如ul):

document.querySelector('ul').addEventListener("click", function(e) {
  console.log(e.target); // this will helps us to figure out on what exact element a click was made
  console.log("clicked");
})

答案 2 :(得分:0)

您可以像这样遍历按钮:

let li = document.getElementsByTagName("li");

let buttons = document.getElementsByTagName("span");

[].forEach.call(buttons, function(button) {
    button.addEventListener("click", function() {
        console.log("You clicked!");
    });
});