JS implementation adds event function examples for dynamically added elements [event-based delegation], js examples

Source: Internet
Author: User
Tags function examples

JS implementation adds event function examples for dynamically added elements [event-based delegation], js examples

This example describes how to add events to dynamically added elements in JavaScript. We will share this with you for your reference. The details are as follows:

In daily development, we sometimes use js to create some elements. However, if we use the original for loop to add events to the created node, the method will not work:

<! DOCTYPE html> 

Running effect:

For example, the events added to li through the for loop cannot be bound to the newly added li. The detailed reasons are not explained here. Then how can we solve this problem? In fact, the solution is simple, that is, through the event Delegate method, directly go to the Code, and the above Code is simply transformed:

<! DOCTYPE html> 

Running effect:

In this way, even the newly added li click event can be triggered. However, the detailed method of jquery is not described here. The solution principles of native js and jquery are actually the same. I believe you have understood the native, And the jquery method can be well understood.

PS:About javascript event description can refer to the site javascript events and function description Daquan: http://tools.jb51.net/table/javascript_event

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.