When you bind an event to a DOM element with jQuery , use the following method:
<button class= "Dynamic-bind" > button one </button>$ (function () {$ ('. Dynamic-bind '). On (' click ', Function (e) { alert (E.type); ' Click '});
Then if you add a new DOM element that is identical to the selector by JQuery after the binding event :
$ ('. Dynamic-bind:last '). After (' <buttonclass= "dynamic-bind" > button two </button> ');
in the browser, click Button Two , the alert prompt does not pop up , However, adding DOM elements through JQuery is a very common issue that must be addressed, usually in the following two ways.
1. encapsulate the binding event into a method:
var dynamicbind = function ($element, event) {$element. On (event, function (e) {alert (e.type); });};
The method is then called after each DOM element is added with jQuery:
$ ('. Dynamic-bind:last '). After (' <buttonclass= "dynamic-bind" > button two </button> ');d ynamicbind ($ ('. Dynamic-bind:last '), ' click ');
this solves the problem, but every time you add a DOM elements have to invoke a binding event method, which is not only easy and too low .
2. use The event delegation mechanism of JQuery:
The so-called jquery Event delegation mechanism can be simply understood as jquery automatically attaches an event handler to the matching element, even if the element is added after the delegate declaration. This still uses on to delegate events, but the parameters are slightly different:
$ (document). On (' click ', '. Dynamic-bind ', ' Hello ', function (e) {alert (e.data);//' Hello '});
This way , no matter how many <button class= "Dynamic-bind" ></button>,jquery The Click event is automatically bound to it , and the problem is resolved perfectly. It is important to note that the ' Hello ' parameter here is not mandatory, and if passed in, it is assigned to E.data , which is passed in just to understand the event object.
Add:
1. in earlier versions of JQuery , event delegation and decommissioning were using . Live (). Die (). Delegate (). Undelegate () , approximately In the later versions of jquery 1.9 , these methods were canceled and replaced by the . On (). Off () method, which throws an exception if the. Live () method is used in a higher version of jquery.
2. When an event is delegated, it may not be possible to use only $ (document). On (...); In this way, the $ (document) can be used for any delegated object's parent DOM Ganso, such as:
<div id= "Btn-father" > <button class= "dynamic-bind" > button one </button></div>
Event delegation can also be written as:
$ (' #btn-father '). On (' click ', '. Dynamic-bind ', ' Hello ', function (e) {alert (e.data);});
Finish.
Resources:
http://www.zhidao91.com/jquery-on-no-effective/
This article is from the "barrel of fake dog excrement" blog, please be sure to keep this source http://xitongjiagoushi.blog.51cto.com/9975742/1660706
Work accumulation (vi)--jquery implement DOM element event binding