JQuery dynamically adds elements and binds events

Source: Internet
Author: User

Question 1: The method for creating a new tag is not bound, $ ("li "). bind ("click", clickLi) is executed only once during document ready. The newly added li does not bind the clickLi method:

$ ("Li"). bind ("click"

Question 2: repeat binding. $ ("li") is an array, including all the li Resources in the document. Therefore, the old tag is rebound and the clickLi method is executed multiple times:

$ ("Li"). bind ("click" $ ("li"). bind ("click"

Therefore, when the newly added element is bound to an event, (1) Add it once and bind it once; (2) bind only the newly added element and use the selector such as id and class.

You can also write the corresponding event to html when adding an element, such as onclick = "".

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.