$ (function () { $ (". Div"). Click (function () { var h = ""; for (Var i=0;i<5;i++) { H + = "Here I add every click on <div class= "H3" > Finally add 5 lines $ (". h3"). On ("Click", "H3", {foo: "Text:"},function (event) {
alert (event.data.foo+this.textcontent);
});
Is it easy to choose <div class= "H3" > as the parent element to invoke the on method binding click event so that all elements under the parent element are bound to the Click event, and sometimes do not need to bind all of them? OK, just add the selector after "click" (That is, the child element you want to select), {foo: "Text:"}: The data passed to Event.data (parameter), in the handler we can call Event.data.foo to read the value of the passed function. Open the Browser debugging tool you can also get
In short, remember that if you want to bind dynamically generated element events, you must first find his parent element (the parent element cannot be dynamically generated, otherwise continue to look up), bind in the parent element, and then filter on OK, yes, I tested the hover event found no, did not go to the reason.
First, the problem description
After adding an HTML code dynamically with the jquery Append () method, it was found that the new element could not be obtained when binding the click event for the newly added element.
Second, the solution
The method of Niang recommendation is basically using the live () method
Official definition and usage of live ():
The live () method attaches one or more event handlers to the selected element, and specifies the function to run when these events occur. The event handlers attached through the live () method apply to the current and future elements of the matching selector (such as new elements created by the script).
Live () can be used to view jquery Live ()
The difference between live () and bind () is that live can not only bind events to existing elements in the page, but also add time to the elements that will be added dynamically in the future.
So I replaced bind () with live (), but reported a new error: TypeError: $ (...). Live is not a function
After the query found that the original jquery 1.9 and above have been unable to use Live (), you can use the on () method instead of live ().
The official definition and usage of on ():
The on () method adds one or more event handlers on the selected element and child elements. Since JQuery version 1.7, the On () method is a new alternative to the Bind (), Live (), and Delegate () methods.
Note: The event handlers added using the on () method apply to current and future elements (such as new elements created by the script).
The detailed use of on () can be viewed by jquery on ()
Three, the code demonstration
HTML page:
?