Solve the doubts on the previous jquery

Source: Internet
Author: User

The content is from: http://www.365mini.com/page/jquery-on.htm. Here to do a Collection. the final questions and answers to the article can solve all the doubts and look after the whole article can be better.

on()function is used to bind event handlers for one or more events of the specified element .

In addition, you can also pass on some of the required data to the event Handler.

Starting with jquery 1.7, The on() function provides all the functionality required to bind an event handler to unify the previous event functions such as Bind (), delegate (), and live ().

on()Supports binding events directly on the target element, and also supports delegating bindings on the ancestor elements of the target Element. In the event delegate binding mode, the on() bound event handler is valid even if the newly added element after the function is executed, as long as it meets the Criteria.

In addition, the function can bind multiple event handlers for the same element, the same event Type. When the event is triggered, jquery executes the bound event handler sequentially in the order in which it is bound.

To remove on() an event through binding, use the off () Function. If you want to attach an event, execute only once, and then delete yourself, use the one () Function.

The function belongs to an jQuery object (instance).

Grammar

JQuery 1.7 adds this Function. It is mainly used in the following two forms of Usage:

Usage One :

Jqueryobject.on (events [, selector] [, data], handler)

Usage two :

Jqueryobject.on (eventsmap [, selector] [, data])
Parameters
Parameters Description
Events String type one or more space-delimited event types and optional namespaces, such as "click", "focus click", "keydown.myplugin".
Eventsmap An object object that has each property corresponding to the event type and optional namespace (parameter events ) that corresponds to the event handler (parameter) of the binding handler .
Selector optional/string Type a jquery selector that specifies which descendant elements can trigger the bound Event. If the argument is null or is omitted, the current element itself is bound to an event (the actual trigger may also be a descendant element as long as the event flow reaches the current element).
Data When an optional/arbitrary type triggers an event, any data that is passed to the event handler via Event.data is Required.
Handler The function type specifies the event Handler.

For the events optional namespaces in the parameters, refer to the sample code at the Bottom.

With respect to parameters selector , you can simply understand that if the argument is equal null or omitted, the current matching element is bound to the event, otherwise the selector element binding event in the descendant element of the current matching element conforms to the Selector.

The handler DOM element in the parameter that this triggers the event in the descendant element of the current matching Element. If the argument is selector equal null to or omitted, it points to the this current matching element (that is, the element).

on()handleran Event object that represents the current event is also passed as a parameter.

handlerThe return value of the parameter is consistent with the return value of the handler function for the native event of the DOM. For example, the event handler function for the "submit" (form Submission) event returns false , which prevents the form from being Submitted.

If the event handler handler is just a return false value, it can be handler set directly to false .

return value

  

on()The return value of the function is the jquery type, which returns the current jquery object itself.

Important Notes :

If arguments are passed selector , the on() function does not bind event handlers for the elements that match the current jquery object, but instead binds the event handler to the element in their descendant element that conforms to the selector selector parameter. on()instead of binding events directly for these descendant elements, the function delegates to the matching elements of the current jquery object to Handle. Because of the DOM 2-level event flow mechanism, when a descendant element selector fires an event, the event is passed to all its ancestor elements in the event bubbling, and when the event stream passes to the current matching element, jquery determines which descendant element triggered the event, and if that element conforms to the selector selector , jquery captures the event and executes the bound event Handler.

It is easy to say that if we want to bind the Click event handler to all <P> tags on the page, we can bind the click event handler directly on each P Tag. For example:

  

// for all P elements, bind the click event handler separately handler$ ("p"). on ("click", handler);

We can also bind the event-delegation mechanism to any of these P-tag's common ancestor elements, using the Dom's event bubbling mechanism to unify the delegate Processing. When we trigger the Click event for an element, JS notifies the element and its "parent" element, the "grandfather generation" element, in turn ... Until the topmost document object, if the elements are bound, the Click event handler is executed Sequentially.

// bind the Click event handler to the BODY element handler, if the Click event is triggered by the P element of its descendants, execute handler$ (document.body). on ("click", "p", handler);

In the example here, the event delegation mechanism is that we do not bind the Click event handler directly for each p element, but instead delegate it to a common ancestor element (in The example here document.body ) and "tell" him: If you receive the Click event Trigger notification, And this click event is triggered by one of our P elements, which executes the event handler of the delegate binding on the ancestor Element.

Note : Some events, such as "focus", "blur", do not support bubbling, and using the event delegation mechanism will be INVALID. however, They also generally have corresponding events that support Bubbling. For example, "focusin" corresponds to "focus" and "focusout" corresponding to "blur". In addition, we can use the Event.stoppropagation () method to let the currently triggered event stop Bubbling.

Example & Description

As an example of a click event ("click"), the following is the general use of event functions in jquery (some functions also have other forms of usage, which are not listed here):

//here the selector selector is used to specify the element that can trigger the event//The selector ancestor here should be the ancestral element of selector, and the event triggered by selector can be captured in the event stream by its ancestral elements, triggering the event in the form of "proxy". //jQuery 1.0+ (1.4.3+ support parameter Data)$ ("selector"). Click ([data,] handler);//jQuery 1.0+ (1.4.3+ support parameter Data)$ ("selector"). Bind ("click")[, data], handler);//jQuery 1.3+ (1.4+ support parameter Data)$ ("selector"). Live ("click")[, data], handler);//jQuery 1.4.2+$ ("ancestor"). Delegate ("selector", "click"[, data], handler);//jQuery 1.7+$ ("ancestor"). on ("click", "selector" [, data], handler);

Please refer to the following initial HTML code:

<div id= "n1" >    <p id= "n2" ><span>CodePlayer</span></p>    <p id= "n3" >< Span> focus on programming development technology sharing </span></p>    <em id= "n4" >http://www.365mini.com</em> </div><p id= "n5" >Google</p>

We bind a fixed-point event for all <p> elements in <div>:

// binds the Click event handler for all P elements in the div // only n2, N3 can trigger the event function () {    //  This here points to the P element (element)    alert ($ (this) thattriggers the Click event. Text ());});

If you want to bind all the <p> elements, you can write the following jquery code:

// bind the Click event handler for all P elements (note: the selector parameter is omitted Here) // n2, n3, N5 can trigger this event function (event) {//  This here points to the P element (element) alert that triggers the Click event    ($ (this). text ());});

In addition, we can bind multiple events at the same time and pass some additional data for the event handler, which we can do with jquery for the arguments passed in by the event handler function (the event event object):

vardata = {id:5, name: "zhang san" };//bind MouseEnter MouseLeave two events for N5 and pass in additional data for it//additional data can be any type$ ("body"). on ("mouseenter mouseleave", "#n5", data,function(event) {var$me = $ ( this); varoptions = event.data;//This is the incoming additional Data.    if(event.type = = "mouseenter"{$me. HTML ("hello," + options.name + "!"); }Else if(event.type = = "mouseleave"{$me. HTML ("good-bye!"); }           });

In addition, even if the qualifying element is on() newly added after the function executes, the binding event is still valid for it. As an example of the initial HTML code, we can write the following jquery code:

// binds the Click event handler for all P elements in the div // only n2, N3 can trigger the event function (event) {    Alert (this). text ());}); // the N6 added later can also trigger the click event, as it is also the P element in the div $ ("#n1"). append (' <p id= ' N6 ' > The click event for the above binding also takes effect on this element!</p> ') ;

eventsThe parameter also supports attaching additional namespaces for the event Type. When you bind multiple event handlers of the same type to the same element. Using namespaces, you can limit the range that is triggered or removed when an event is triggered or removed.

functionclickhandler (event) {alert ("namespace when triggered: [" + event.namespace + "]");}var$p = $ ("p");//A: Bind the Click event for all P elements, defined under Foo and bar two namespaces$p. on ("click.foo.bar", clickhandler);//B: Bind the Click event for all P elements, defined under the test namespace$p. on ("click.test", clickhandler);var$n 2 = $ ("#n2");//trigger All Click events$n 2.trigger ("click");//triggers A and b (event.namespace = "")//triggers the Click event defined under the Foo namespace$n 2.trigger ("click.foo");//trigger a (event.namespace = "foo")//trigger the Click event defined under the bar namespace$n 2.trigger ("click.bar");//trigger a (event.namespace = "bar")//triggers a Click event that defines both the Foo and bar two namespaces$n 2.trigger ("click.foo.bar");//trigger a (event.namespace = "bar.foo")//trigger the Click event defined under the test namespace$n 2.trigger ("click.test");//Trigger B (event.namespace = "test")//removes all P elements defined by the Click event handler in the Foo namespace$p. off ("click.foo");//Remove a

on()A Function's argument eventsMap is an object that can specify multiple event Type-handler functions in the form of a Property-value. The corresponding sample code is as Follows:

var data = {id:5, name: "zhang san" }; var events = {    function(event) {        $ (this). HTML ("hello," + Event.data.name + "!" );           },        function(event) {        $ (this). HTML ("good-bye!") );    }       }; // bind MouseEnter MouseLeave two events for N5 and pass in additional data for it("body"). on (events, "#n5", data);

User Questions:

The binding event remains in effect even if the eligible element is newly added after the on () function is Executed. This is wrong, I experimented with the next $ (' p '). on (' click ', function () {
Alert (this). Text ());
});
$ (' body>div '). append ($ (' <p>sssssaa</p> ')); Post-add P does not have an event

Landlord Answer:

pro, you are not using it. You look good on the api, especially the "important notes" in the Article.
On () If the selector parameter is not passed, then it is the direct binding, not the event delegation mechanism; if the selector parameter is added, that is the event delegate, then the newly added element, as long as the condition is met, the binding event is still VALID.
For example, to bind the click event to all P tags in the page, this should be the Case:
$ (document.body). on ("click", "p", function () {});
This way, the newly added P element will also bind the click Event.
In depth, This click event is actually bound to the Document.body above, not each p tag, but all its descendant nodes emit a click event that bubbles through to document.body and triggers the Click event of its binding. jquery re-detects If the Click event "passed" the "p" tag in the bubbling process, and if so, executes the callback function we Specified.

I have also made an example:
<!        DOCTYPE html>            $(function() {                $("div"). on ("click",function() {                    $("#aa"). Append ("<span>12121 </span>")                }); //the Click event can be triggered$ ("div"). on ("click", "span",function() {alert (1236)                }); //the Click event cannot be triggered$ ("span"). on ("click",function() {alert (1236)                });        }); </script> Click here</div> </body>

Solve the doubt on the previous jquery

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.