Home  >  Article  >  Web Front-end  >  Two methods to solve the problem that dynamically added element nodes cannot trigger events in jquery_jquery

Two methods to solve the problem that dynamically added element nodes cannot trigger events in jquery_jquery

WBOY
WBOYOriginal
2016-05-16 15:34:271323browse

For example, when making an ajax to read the message list, there is a reply button behind each message with the class "reply". If you use $(".reply").click(function(){ // do something... }), presumably the click event of the reply button in the list loaded later through ajax will be invalid.

ActuallyThe simplest way is to write onclick="" directly in the tag, but writing this way is actually a bit low. The best way is to bind it to the class name Set a click event.

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

In order to achieve a better demonstration effect, assume that there is code with the following structure under the body of a page:

<p id="pLabel">新加一条</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>'); //动态像ul的末尾追加一个新元素
});
</script>

Method 1: Use live

The

live() function will bind one or more event handlers to the selected element and specify the functions to be run when these events occur. The live() function is applied to current and future elements matching the selector. For example, elements created dynamically through scripts.

The implementation is as follows:

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

Method 2: Use on

You can bind events through the on method, which can be bound to its parent or body. The implementation is as follows:

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

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn