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 one </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 try again, and there will be no problem.