事件未附加在来自服务器响应的元素上

时间:2019-04-13 22:21:31

标签: javascript php html

我有许多名为“ abc”的div,我在它们的名称上添加了一个事件监听器,它们工作正常,但是当我从服务器的响应中获得相同的div时,事件将解除绑定。

This is my div

This is my script for adding an event

This is the result before getting response

This is after getting the response

这些工作正常

<div class="row" style="">
<div class="col-lg-12 col-md-12 col-sm-12 h-col" id="h-col">
<div class=" hero-rows">
<div class=""id="Strength" name="nature"><h5>STRENGTH</h5> 
</div>
</div>
</div>
</div>
<div class="row" style="">    
<div class="col-lg-12 col-md-12 col-sm-12 h-col" id="h-col">
<div class=" hero-rows">
<div class="" id="AGILITY" name="nature" ><h5>AGILITY</h5> 
</div>
</div>
</div>
</div>
<div class="row" style="">
<div class="col-lg-12 col-md-12 col-sm-12 h-col" id="h-col">
<div class=" hero-rows">
<div class="" id="INTELLIGENCE" name="nature" > 
<h5>INTELLIGENCE</h5></div>
</div>
</div>
</div>

这是我的脚本。

var nature = document.getElementsByName('nature');

for(var i =0; i< nature.length; i++)
{
nature[i].addEventListener('click',function()
{
    heroNatureFilter(this.id);
});
}

1 个答案:

答案 0 :(得分:0)

您需要了解事件绑定的工作原理。在HTML元素或元素集上绑定事件时,事件将绑定到该页面上当前的元素。这并不意味着它将绑定到绑定事件时不可用的将来元素。

当服务器返回响应并将这些元素添加到页面时,绑定的事件处理程序将不适用于它们,因为绑定事件时它们不存在。为了使他们能够响应所讨论的事件,您必须调用代码以再次绑定事件。这次,由于这些元素在页面上,因此事件绑定将应用于它们。一种简单的方法是将事件绑定调用封装在一个函数中。

在您的情况下,您必须包含以下部分:

var nature = document.getElementsByName('nature');

for(var i = 0; i < nature.length; i++) }{
   nature[i].addEventListener('click', function() {
      heroNatureFilter(this.id);
   });
}

在函数中,例如:

function bindEvents() {
    var nature = document.getElementsByName('nature');

    for(var i = 0; i < nature.length; i++) }{
       nature[i].addEventListener('click', function() {
          heroNatureFilter(this.id);
       });
    }
}

然后,当服务器响应返回时,您必须调用函数将事件绑定到新返回的元素:

bindEvents();