There are two ways to solve the problem of not triggering events for dynamically added element nodes in jquery

Source: Internet
Author: User

There are two ways to solve the problem of a dynamic new element node in jquery that cannot trigger an event , as follows:

To achieve a better presentation, assume that there is code for the following structure under the body of a page:

?
1234567891011 <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 One: Use Live

The live () function binds the selected element to the previous or multiple event handlers, and specifies the function to run when these events occur. The live () function works with the current and future elements of the matching selector. For example, elements created dynamically through a script.

The implementation is as follows:

?
123 $(‘.liLabel‘).live(‘click‘, function(){ alert(‘OK‘);});

Method Two: Use on

You can bind an event by using the on method, which can be bound to its parent or body, as follows:

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

Now we can try to try, whether the problem has been solved, I hope this article can really help everyone.

There are two ways to solve the problem of not triggering events for dynamically added element nodes in jquery

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.