addEventListener问题

时间:2018-05-28 03:05:05

标签: javascript dom

所以我应用了我最近对Javascript和DOM的了解。但是,我收到的错误消息是" addEventListener未定义"当我尝试使用querySelectorAll或getElementsByClassName作为相同的按钮时,但针对不同的问题。这是我的代码块。

var input = document.getElementsByClassName('userInput');
var submitButton = document.getElementsByClassName('.submit');
var numAnsCorrect = 0;
var numAnsIncorrect = 0;
var questionsRight = document.querySelector('.questionsRight');
var questionsWrong = document.querySelector('.questionsWrong');


submitButton.addEventListener('click', () => {
    let submitButton = document.querySelector('.submit');
    let userInput = document.querySelector('.userInput');
    let response = userInput.value;
    response = response.toUpperCase();
    var answer = ['SAVANNAH', 'NATHAN DEAL'];
    let result = document.querySelector('.question-result');
    for (var i = 0; i < answer.length; i++) {
        if (response === answer[i]) {
            result.textContent += ' That is correct!';
            numAnsCorrect++;
            questionsRight.textContent = numAnsCorrect;
            submitButton.style.display = "none";
        } else {
            result.textContent += ' That is incorrect';
            numAnsIncorrect++;
            questionsWrong.textContent = numAnsIncorrect;
            submitButton.style.display = "none";
        }
    }
});

我做错了什么?我假设我必须遍历按钮或者可能有另一个等于运算符的按钮,但我不太确定。

3 个答案:

答案 0 :(得分:1)

当您使用querySelectorAll()getElementsByClassName()时,您会收到一个元素列表。您需要从该列表中提取一个元素才能在其上调用addEventListener()

示例:

var userInputs = document.getElementsByClassName('userInput');
var input = userInputs[0];

答案 1 :(得分:1)

不能确定OP代码有什么问题,因为HTML没有提供,但是我可以放心地假设有一些元素你想要倾听事件。有几种方法可以实现您的目标:

  1. 使用循环或数组方法迭代多个元素。当前元素On each loop assign an event handler

    for (let i=0; i < list.length; i++) {
      list[i].addEventListener('click', eventHandler);
    } 
    
  2. 为每个元素分配on event attribute

    <button onclick='eventHandler()'>CLICK</button>
    <button onclick='eventHandler()'>CLICK</button>
    
  3. Event Delegation是一种利用Event BubblingEvent Object的模式。基本上,如果我们需要监听事件的一组元素,我们只需将一个eventListener 分配给元素组共有的祖先元素(我们甚至可以使用{{1 }}或document。)这样做,我们的资源不会绑定在几个eventHandlers / eventListeners中,我们不会在100次onclick事件中输入Carpal Tunnel Syndrome。⭐推荐

  4. 演示1

    在NodeList或数组的每次迭代中注册eventHamdlers / eventListeners

    &#13;
    &#13;
    window
    &#13;
    /* Collect all .btn class in a NodeList then convert it into
    || an array
    */
    var btnArray = Array.from(document.querySelectorAll('.btn'));
    
    // Reference the output.out
    var out = document.querySelector('.out');
    
    /* run arry through forEach() array method...
    || on each loop assign an onclick eventHandler or eventListener to
    || current button.btn
    */
    btnArray.forEach(function(btn, idx) {
    
      btn.addEventListener('click', function() {
    
        var txt = btn.textContent;
    
        out.textContent = txt;
        
      });
    
    });
    &#13;
    .out,
    button {
      display: inline-block;
      color: blue;
      font: 900 20px/1 Consolas;
      width: 5ch;
      text-align: center;
    }
    
    .out {
      color: red;
      width: 100%;
      font-size: 30px
    }
    &#13;
    &#13;
    &#13;

    演示2

    为每个元素

    分配on事件属性

    &#13;
    &#13;
    <fieldset class='set'>
      <button class='btn'>BTN0</button>
      <button class='btn'>BTN1</button>
      <button class='btn'>BTN2</button>
      <button class='btn'>BTN3</button>
      <button class='btn'>BTN4</button>
      <button class='btn'>BTN5</button>
      <button class='btn'>BTN6</button>
      <button class='btn'>BTN7</button>
      <button class='btn'>BTN8</button>
      <button class='btn'>BTN9</button>
      <button class='btn'>BTNA</button>
      <button class='btn'>BTNB</button>
      <button class='btn'>BTNC</button>
      <button class='btn'>BTND</button>
      <button class='btn'>BTNE</button>
      <button class='btn'>BTNF</button>
      <output class='out'>X</output>
    </fieldset>
    &#13;
    var out = document.querySelector('.out');
    
    function eventHandler(event) {
      var txt = event.target.textContent;
      out.value = txt;
    }
    &#13;
    .out,
    button {
      display: inline-block;
      color: blue;
      font: 900 20px/1 Consolas;
      width: 5ch;
      text-align: center;
    }
    
    .out {
      color: red;
      width: 100%;
      font-size: 30px
    }
    &#13;
    &#13;
    &#13;

    <小时/>

    演示3

    事件代表团

    在演示中评论的详细信息

    推荐

    &#13;
    &#13;
    <fieldset class='set'>
      <button class='btn' onclick="eventHandler(event,this)">BTN0</button>
      <button class='btn' onclick="eventHandler(event,this)">BTN1</button>
      <button class='btn' onclick="eventHandler(event,this)">BTN2</button>
      <button class='btn' onclick="eventHandler(event,this)">BTN3</button>
      <button class='btn' onclick="eventHandler(event,his)">BTN4</button>
      <button class='btn' onclick="eventHandler(event,this)">BTN5</button>
      <button class='btn' onclick="eventHandler(event,this)">BTN6</button>
      <button class='btn' onclick="eventHandler(event,this)">BTN7</button>
      <button class='btn' onclick="eventHandler(event,this)">BTN8</button>
      <button class='btn' onclick="eventHandler(event,this)">BTN9</button>
      <button class='btn' onclick="eventHandler(event,this)">BTNA</button>
      <button class='btn' onclick="eventHandler(event,this)">BTNB</button>
      <button class='btn' onclick="eventHandler(event,this)">BTNC</button>
      <button class='btn' onclick="eventHandler(event,this)">BTND</button>
      <button class='btn' onclick="eventHandler(event,this)">BTNE</button>
      <button class='btn' onclick="eventHandler(event,this)">BTNF</button>
      <output class='out'>X</output>
    </fieldset>
    &#13;
    // Reference the parent element
    var set = document.querySelector('.set');
    
    /* Register parent to click event it will trigger not only when 
    || it is clicked, it will also trigger callback if any of ts 
    || descebdant elements are clicked as well.
    */
    set.addEventListener('click', eventHandler);
    
    // Callback function passes the Event Object
    function eventHandler(even) {
    
      // Reference an output.out
      var out = document.querySelector('.out');
    
      // if the clicked element (event.target) has the class .btn...
      if (event.target.className === "btn") {
    
        // ...Get event.target's text
        var txt = event.target.textContent;
    
        // Display the text
        out.value = txt;
      }
    
      return false;
    
    };
    &#13;
    .out,
    button {
      display: inline-block;
      color: blue;
      font: 900 20px/1 Consolas;
      width: 5ch;
      text-align: center;
    }
    
    .out {
      color: red;
      width: 100%;
      font-size: 30px
    }
    &#13;
    &#13;
    &#13;

答案 2 :(得分:-1)

我之前有这个问题。在 submitButton 上尝试console.log。但在某些情况下,获取DOM元素的最佳方法是使用getElementsById。或者使用JQuery进行高级目的。