Two ways to solve the problem of dynamically newly added element nodes in jquery not being able to trigger events

  • 2020-09-16 07:23:40
  • OfStack

For example, when reading a list of comments, there is a reply button at the end of each comment, class is "reply", if you are using $(".reply ").click (function(){//do something... }), presumably the reply button in the list loaded by ajax later will become invalid if the event is clicked.

The easiest way to do this is to write onclick="" in the tag, but this is a bit low, and the best way to do it is by binding an click event to the class name.

There are two solutions to the problem that dynamically added element nodes in jquery cannot trigger events, as follows:

For better illustration purposes, assume that body on a page has the following code structure:


<p id="pLabel"> New added 1 article </p>
<ul id="ulLabel">
 <li class="liLabel">aaa1</li>
 <li class="liLabel">aaa2</li>
 <li class="liLabel">aaa3</li>
</ul>
<script type="text/javascript">
$("#pLabel").click(function(){
 $("#ulLabel").append('<li class="liLabel">aaaQ</li>'); // Dynamic like ul End append 1 A new element 
});
</script>

Approach 1: Use live

The live() function binds one or more event handlers to the selected element and specifies the function to run when these events occur. The live() function applies to match the current and future elements of the selector. For example, an element created dynamically through a script.

The implementation is as follows:


$('.liLabel').live('click', function(){
 alert('OK');
});

Approach 2: Use on

An event can be bound to its parent or to body via the on method, which is implemented as follows:


$("#ulLabel").on('click','.liLabel',function(){
 alert('OK')
});
 Or: 
$("body").on('click','.liLabel',function(){
 alert('OK')
});

Now you can try to see if the problem has been solved, I hope this article can really help you.


Related articles: