jquery adds events for dynamic add elements
And here:http://www.cnblogs.com/dumuqiao/archive/2011/09/09/2172511.html
Event names and namespaces (incident name and namespace)
http://www.css88.com/jqapi-1.9/on/
The name of any event can be used as a events parameter. jquery will pass the standard JavaScript event type for all browsers, when the user is manipulating events, such as the click function that the browser invokes handler parameters. In addition, the .trigger() method can trigger a handler for standard browser events and custom event name bindings.
Event name you can add the specified event namespaces (namespace) to simplify deleting or triggering events. For example, "click.myPlugin.simple" two namespaces myplugin and simple are defined for the Click event. The Click event handler, which is bound by the above method, can be used .off("click.myPlugin") or .off("click.simple") deleted to bind to the corresponding element's click event handler without interfering with the "click" event that is bound to the element. Namespaces are similar to CSS classes because they are hierarchical, and only one name is required to match. Namespaces that start with the underscore are for jQuery.
In the .on() second use of a method, events a parameter is a JavaScript object or a key-value pair. The key is equal to the events argument, separated by a space between the event name string and the optional namespace. The value of each key is a function (or false value) equivalent to a handler parameter, but the value is not the last parameter in the method. In other respects, the two forms behave identically in the content described below. As described below.
The difference between. bind (),. Live (), and. Delegate () is not obvious. But understanding their differences helps to write more concise code and prevents unexpected bugs in our interactive programs.
Basic
DOM Tree
First, a graphical HTML document can help us understand better. A simple HTML page should look like this
event Bubbling (also known as event delivery) (Events bubbling aka event propagation)
Clicking a link triggers the Click event bound to the link element, which in turn triggers the function that binds to the click event of the element.
?
| 1 |
$(‘a‘).bind(‘click‘, function() { alert("That tickles!") }); |
So a single click triggers an alert.
The Click event is then passed up from the DOM tree, propagated to the parent element, and then passed to each ancestor element.
In the DOM tree, document is the root node.
Now we can easily explain the difference between bind (),. Live (), and. Delegate ()
. Bind ()?
| 1 |
$(‘a‘).bind(‘click‘, function() { alert("That tickles!") }); |
This is the most straightforward method of binding. JQuery scans the document to find all the $ (' a ') elements and then gives each of the found elements the Click event Binding handler function.
. Live ()?
| 1 |
$(‘a‘).live(‘click‘, function() { alert("That tickles!") }); |
jquery binds the handler function to the $ (document) element and takes ' click ' and ' a ' as arguments to the function. When an event bubbles to the document node, check that the event is not a click event, and the target element can match the ' a ' CSS selector if two conditions are true and the processing function executes.
The live method can also be bound to the specified element (or "context") without binding to the document, such as:
?
| 1 |
$(‘a‘, $(‘#container‘)[0]).live(...); |
. Delegate ()?
| 1 |
$(‘#container‘).delegate(‘a‘, ‘click‘, function() { alert("That tickles!") }); |
The jquery scan document finds $ (' #container '), binds the handler function to his click event, ' a ' CSS selector as a function parameter. When there is an event bubbling to $ (' #container '), check that the event is not a click, and check that the target element is not matching the CSS selector, if both are compliant, execute the function.
Note that this time is very similar to the. Live () method, except that the event is bound to a specific element and differs from the element. The savvy JS ' er may be summed up into $ (' a '). Live () = = $ (document). Delegate (' A '), is that really the case? No, not all of it.
why. Delegate () ratio. Live () Good
The delegate method of JQuery should be preferred more than the live method for a reason. Consider the following scenario:
?
| 123 |
$(‘a‘).live(‘click‘, function() { blah() });// or$(document).delegate(‘a‘, ‘click‘, function() { blah() }); |
Speed
The second above executes faster than the first because the first one will traverse the entire document to look up the $ (' a ') element and save it as a jquery object, but the live method only needs to pass a string parameter ' a ', the $ () method does not know that we will use the chain expression in the back. Live ().
The delegate method only needs to find and store the $ (document) element enough.
One of the hack is to call the live method outside of the $ (document). Ready (), so that it executes immediately. At this point the DOM is not populated, and no elements are found or jquery objects are created.
flexibility and chained syntax
The live approach is still confusing. Think about it chained to the $ (' a ') object, but actually it works in the $ (document) object. For this reason, it is disturbing to use live in chained expressions, and I think the live method becomes a global jquery method $.live (' A ',...) makes more sense.
only CSS selectors are supported
Finally, the live method has one of the biggest drawbacks, only with CSS selectors, it is inconvenient to use.
For the disadvantages of CSS selectors, see Exploring JQuery. Live () and. Die ().
Original Author update
why use. Live () or. Delegate () instead of. Bind ()
Finally, the Bind method looks clearer and more straightforward, isn't it? But there are two reasons why we recommend delegate or live:
- Binds an event handler to an element that does not yet exist in the DOM. The Bind method binds the function directly to each individual element and cannot be bound to an element that has not yet been added to the page if you have written $ (' a '). Bind (...) and then use Ajax to add new links to the page, and the newly Added link will not bind the event. Live or delegate or other events that are bound to ancestor elements, so that existing elements, or elements that are added later, can be used.
- The binding handler functions to an element or a few elements, listening to the descendant elements, rather than binding 100 identical processing functions to individual elements. This is more of a performance advantage.
Stop bubbling
Finally, notice the event bubbling. Usually we can block other processing functions in such a way:
?
| 12345 |
$(‘a‘).bind(‘click‘, function(){e.preventDefault();//ore.stopPropagation();}) |
In fact, the event about the deletion of live has already been notified in 1.7. After the 2 release, it has been advocated. In instead of. Live events have been used in the process.
Updated today to see the jQuery1.9 of the information found in the API has been completely removed. Live Event
I'm guessing there's someone about the. On event that did not have previous. Live events so good to use even when there is no event bound
In fact, this is the answer. The on event differs from the previous use of. Live and. Bind events:
$ (' Selecter '). Live (' click ', function () {//do something ...});
The To. On event should look like this:
$ (document). On (' Click ', ' Selecter ', function () {//do something ...});
The. On event can completely replace the previous. Bind,. Delegate and other events
Bind
$( "#members Li a" ).On( "Click", function(E) {} );
$( "#members Li a" ).Bind( "Click", function(E) {} );
Live
$(Document).On( "Click", "#members Li a", function(E) {} );
$( "#members Li a" ).Live( "Click", function(E) {} );
Delegate
$( "#members" ).On( "Click", "Li a" , function ( e {} Span class= "pun");
$ ( "#members" Span class= "PLN" > ). delegate ( "Li a" , "click" , function ( e {}
But here, events bound with the live or delegate methods are passed to the point where the event is actually bound. At this point the other functions have been executed.
We previously defined events, such as defining a click event for an element, which is written like this:
The code is as follows:
$ (' input '). Click (function () {
Working with Code
});
Or
The code is as follows:
$ ('. ClickMe '). Bind (' click ', function () {
Bound handler called.
});
However, this can only be defined for elements that have already been loaded, and those that later add inserts need to be bound separately. Even if you use jquery's clone function, it does not replicate the event (so far I am not sure why it is so defined, it is not possible to copy or deliberately do so, to prevent some exceptions, it is still to analyze the source code of jquery).
Now, with live you can easily get it done,
$ ('. ClickMe '). Live (' click ', function () {//Live handler called.}); In this way, you will be bound to the event, $ (' body ') even after dynamically inserting the element in the back. Append (' <div class= ' ClickMe ">another target</div> ');
Definition and usage
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).
Issue: Use the jquery Live () method to bind events, sometimes with duplicate bindings, such as when a button is clicked, the event that the button binds to and executes N times.
Workaround: Use the Die () method to dismiss the previously bound event on this element before the live () method binding, and then bind the new event through the Live () method.
JS Code
First by the Die () method, and then by the live () binding
$ ("#selectAll"). Die (). Live ("Click", Function () {
Event Run code
});
First by the Die () method, and then by the live () binding
$ ("#selectAll"). Die (). Live ("Click", Function () {
Event Run code
}) Introduction to;d IE () method:
JS Code
Die ([Type], [fn]) <span style= "White-space:normal" > </SPAN>
Die ([Type], [FN])
Overview
JQuery 1.3 is new. This method is exactly the opposite of live.
If you do not take parameters, all live events that are bound will be removed.
You can remove custom events that are registered with live.
If the type parameter is supplied, the corresponding live event is removed.
If the second parameter function is also specified, only the specified event handler is moved out.
Adding events to jquery dynamically added elements 2