【问题标题】:Losing an event triggering after adding new HTML item添加新 HTML 项后丢失事件触发
【发布时间】:2018-10-10 14:43:27
【问题描述】:

在容器中添加新元素后,事件触发丢失。 示例代码如下。取消注释最后一行 Javascript 后事件丢失

您知道原因以及如何解决此问题吗?

<div class="container">
  <button class="test-item">text</button>
  <button class="test-item">text</button>
  <button class="test-item">text</button>
  <button class="test-item">text</button>
</div>
var allItems = Array.from(document.querySelectorAll('.test-item'));

allItems.forEach(function(item){
   item.addEventListener('click', function(){
   console.log("Go!");
   });
});

var template = "<button class='test-item'>New button</button>";

//document.querySelector('.container').innerHTML += template;

【问题讨论】:

    标签: javascript events dom-events addeventlistener innerhtml


    【解决方案1】:

    重写添加新按钮的代码:

    var template = document.createElement("button");
    template.className = "test-item";
    template.innerHTML = "New Button";
    
    document.querySelector('.container').appendChild(template);
    

    最有可能发生的情况是,当您在容器的内部 html 上使用 += 时,它会完全重新创建子内容。因此,创建了一组全新的按钮,导致任何以前的事件处理程序不再工作。

    【讨论】:

      【解决方案2】:

      你刚刚失去了听众的踪迹。首先,您定义 var allItems ,它返回一个数组,然后为该数组上的每个项目添加一个侦听器。但是随后您在代码的最后一行添加了更多项目,这意味着您现在拥有一组完全不同的数组。所以你的听众都不会工作。

      解决方案很简单,先制作item,然后添加监听器。意思是,将您的 var templatedocument.querySelector('.container').innerHTML += template; 移动到代码的最顶部

      【讨论】:

      • 感谢您的解释,但重点是在添加事件后添加此元素(甚至更多)
      • 我相信你不能在javascript中做到这一点,你必须先有项目然后添加监听器。您的代码逐行执行。当然,如果这是您想要的,您可以延迟该功能。我想澄清一下,定义监听函数后添加项目有什么意义?
      • 我需要根据用户需求添加多个元素。所以在页面上是按钮“添加下一个元素”,点击它后,类.test-item的新元素添加到.container
      • 如果是这种情况,那么您可以在单击按钮后添加功能。您对“添加下一个元素”单击的回调将制作模板,并为其分配侦听器。 addelement.addEventListener('click', function(){ //here, make the template, //and here attach functionality you want for all the template })
      猜你喜欢
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2012-11-26
      • 2013-08-10
      • 1970-01-01
      相关资源
      最近更新 更多