Cliché JS Dynamic Add Event---event delegate _javascript tips

Source: Internet
Author: User

Its so-called dynamic Add event essence refers to the event delegation in JS.

We know that in JS, event handling can only be bound to the currently selected element, in other words, event processing can only be bound to the existing elements of the current document! However, often the small partners will encounter a problem is that my element is later dynamically added to the page, and I want to give the element binding events, how to deal with?

To illustrate the white issue, we assume that you need to add the click event to the element that you later add to the current page.

The core of solving this problem is to use JS's delegate event. The advantage of delegating events is that you can bind events to elements that do not exist, and delegate events tend to cost less!

digression: Give the simplest example: when there are 1000 div on the page, if the div is directly bound to the Click event, it will bind the event to 1000 elements. However, if you use an event delegate, you need only one element binding event. PS: I hope it will let you understand the meaning of the event delegate.

We just want to know how dynamically created elements add events, you say so much to do, what to do ...

All right, let's go to the details:

Simulate dynamic creation element Li
$.ajax ({
  type: ' Get ',
  data: {},
  success:function () {        
    $ (' <li> '). AddClass (' AAA '). HTML (' 11111111 '). Appendto ($ (' body ');
  },
});

Add event $ (document) to the element we just created dynamically
. On (' Click ', ' li[class=aaa] ', function () {
  console.log (' ddd ');
});

The above Cliché JS Dynamic Add Event---Event delegate is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.