【问题标题】:How to addEventListener and function with element as a parameter to multiple elements?如何添加EventListener并使用元素作为多个元素的参数?
【发布时间】:2019-11-20 00:51:03
【问题描述】:

我的目标是当用户点击其中一个单词时,让一堆带有可点击单词的 div 将它们的 id 传递给 Javascript 函数。它完美地适用于

    <div id="wordbox">
        <div id="pd"><h4>pdf</h4><br></div>
        <div id="an"><h3>analysis</h3></div>
        <div id="ai"><h2>artificial intelligence</h2></div>
        <div id="tr"><h4>trends</h4><br><br></div>
        <div id="dm"><h3>data mining</a></div>
    </div>
 var word = document.getElementById("pd");
 word.addEventListener("click", function(){ showSlide(word.id) });

但我无法让它适用于所有元素。这失败了:

  var wb = document.getElementById("wordbox").children;

  wb.forEach(function (element, index){
    element.addEventListener("click", function(){
      showSlide(element.id);
    });
  }); 

有什么想法吗?

【问题讨论】:

    标签: javascript html arrays dom-events


    【解决方案1】:

    当您从一个节点中选择子节点时,它实际上返回一个array-like collection,它与相似,但不完全是array。为了使用forEach,您首先需要将其转换为array,在下面的示例中,我使用spread syntax 将其转换为array,这样我就可以使用forEach

    const wb = document.querySelector('#wordbox')
    const children = [...wb.children]
    
    children.forEach(child => {
      child.addEventListener('click', () => {
        console.log(child.id)
      })
    })
    <div id="wordbox">
        <div id="pd"><h4>pdf</h4><br></div>
        <div id="an"><h3>analysis</h3></div>
        <div id="ai"><h2>artificial intelligence</h2></div>
        <div id="tr"><h4>trends</h4><br><br></div>
        <div id="dm"><h3>data mining</a></div>
    </div>

    【讨论】:

    • 感谢您的解释,我将阅读有关传播语法的信息。可惜我只能接受一个答案。
    【解决方案2】:

    wb 不是一个真正的数组,它是一个类似数组的对象,称为 live HTMLCollection。您可以使用Array.from() 获取数组。你也可以使用document.querySelectorAll()来选择元素

    var wb = document.querySelectorAll("#wordbox > div");
    // new browsers - https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach#bcd:api.NodeList.forEach
    // wb
    // To support older browsers
    Array.from(wb)
      .forEach(function(element, index) {
      element.addEventListener("click", function() {
        console.log(element.id);
      });
    });
    <div id="wordbox">
      <div id="pd">
        <h4>pdf</h4><br></div>
      <div id="an">
        <h3>analysis</h3>
      </div>
      <div id="ai">
        <h2>artificial intelligence</h2>
      </div>
      <div id="tr">
        <h4>trends</h4><br><br></div>
      <div id="dm">
        <h3>data mining</a>
      </div>
    </div>

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 2021-10-09
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多