JQuery binds events to dynamically added elements
This article mainly introduces jQuery's method of binding events to dynamically added elements. It compares the method of event binding in jQuery with the differences between common versions of jQuery and binding, and provides some reference value, for more information, see
This article describes how jQuery binds events to dynamically added elements. Share it with you for your reference. The specific analysis is as follows:
Bind or click is generally used to bind events in jquery, but this can only be used to define events for elements that have been loaded. The elements that are subsequently inserted need to be bound separately. Use live before version 1.7. However, we recommend that you use on later than version 1.8. This section describes how to bind events to dynamically added elements in jQuery.
In actual development, a trigger event is bound to the dynamically generated html element.
For example
?
1 2 3 |
<Div id = "testdiv"> <Ul> </ul> </Div> |
You need to add a click event to the <li> label dynamically added in <ul>.
Previously, jquery 1.7 used live to dynamically bind events.
?
1 2 |
$ ("# Testdiv ul li"). live ("click", function (){ }); |
Use on to dynamically bind events after jquery 1.7
?
1 2 3 |
$ ("# Testdiv ul"). on ("click", "li", function (){ // Do something here }); |
I hope this article will help you with jQuery programming.