简体   繁体   English

将 EventListeners 添加到新创建的 DOM 元素

[英]Adding EventListeners to newly created DOM elements

Hi im currently making a mini project just for practice but i came across this problem.嗨,我目前正在制作一个仅用于练习的迷你项目,但我遇到了这个问题。 The loop work for the hard coded code, but not the dynamiclly type one该循环适用于硬编码代码,但不适用于动态类型一

<button class='agree'>Add Like</button>

then i have a function to basiclly adding number of likes bellow it.然后我有一个 function 基本上在下面添加喜欢的数量。

for(var i = 0; i < agreeBtn.length; i++) {
  agreeBtn[i].addEventListener('click', plusAgree)
}

function plusAgree (e) {
      let newNum =  Number(this.children[1].innerText) + 1;
      this.children[1].innerText = newNum;
}

this code works fine for the hard coded button elements.此代码适用于硬编码按钮元素。 But when i apply it to a new element which i have just created with createElement and innerHTML (dynamicly typed), the event listeners just doesn't work anymore.但是当我将它应用于我刚刚使用 createElement 和 innerHTML(动态类型)创建的新元素时,事件侦听器不再起作用。

    let newDiv = document.createElement('div');
    newDiv.className = 'boxshadow post-div grid-x';
    newDiv.innerHTML = `
    <div class="cell small-10">
          <h3 id='post-title'>${postContent.title}</h3>
          <p id='post-description'>${postContent.description}</p>
        </div>
        <div class="cell small-2 icon-div" id="icon-div">
          <button class='agree' id=${agreeId()}>
            <i class="fas fa-thumbs-up fa-3x"></i>
            <h5 class='agree-num'></h5>
          </button>

how can i change the this for the dynamiclly typed one to refer to the button, instead of the global object?我如何将动态类型的 this 更改为引用按钮,而不是全局 object? thanks谢谢

![ Here is the result for hardcoded ] 1 ![ 这是硬编码的结果 ] 1

![This is what i got from the newly created element ] 2 ![这是我从新创建的元素中得到的] 2

this refers to the global object because the function gets invoked in the global scope. this指的是全局 object,因为 function 在全局 scope 中被调用。

It's best to use the .bind() method here.最好在这里使用.bind()方法。

The bind() method creates a new function that, when called, has its this keyword set to the provided value. bind()方法创建一个新的 function,当调用它时,它的this关键字设置为提供的值。

Here is an example:这是一个例子:

 const agreeBtn = document.getElementsByClassName("agree"); for (var i = 0; i < agreeBtn.length; i++) { const el = agreeBtn[i]; el.addEventListener('click', plusAgree.bind(el)); } function plusAgree(e) { console.log(this); }
 <button id="agree1" class="agree">Agree Button</button> <button id="agree2" class="agree">Agree Button</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM