For example, to do an AJAX read the message list, each message has a Reply button, class is "reply", if you are using $ (". Reply"). Click (function () {//do something ...}), Presumably after the return button in the list that was loaded with Ajax, the Click event will fail.
In fact, the simplest way is to write onclick= "" in the tag directly, but this is a bit low, the best way is by binding a click event to the class name.
There are two solutions to the problem of resolving dynamically new element nodes in jquery that cannot trigger events :
For a better demo, suppose you have code for the following structure under the body of a page:
<p id= "Plabel" > Add a new </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 the end of the UL append a new element
});
</script>
Method One: Use Live
The live () function binds the selected element to the previous or multiple event handlers, and the function that runs when these events occur. The live () function is used to match the current and future elements of the selector. For example, an element that is dynamically created from a script.
Implemented as follows:
$ ('. Lilabel '). Live (' click ', Function () {
alert (' OK ');
});
Method two: Using on
You can bind an event through the on method, which can be bound to its parent or body, as follows:
$ ("#ulLabel"). On (' click ', '. Lilabel ', function () {
alert (' OK ')
});
Or:
$ ("body"). On (' click ', '. Lilabel ', function () {
alert (' OK ')
});
Now we can try, is not the problem has been solved, I hope this article can really help everyone.