Dynamic new element node in jquery cannot trigger event resolution

Source: Internet
Author: User


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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.