JQuery Advanced Events

Source: Internet
Author: User

JQuery not only encapsulates a large number of commonly used event handling, but also provides a number of advanced events for developers to use. such as simulating user-triggered events, event-delegate events, and unified integration on and off, and one method that executes only once. These methods greatly reduce the developer's difficulty and enhance the developer experience. A Analog operation

Sometimes we need some action to simulate the behavior of the user when the event is triggered. For example: When the page is loaded, click on a button to trigger an event instead of the user clicking

//Click Button Events$('input'). Click (function () {alert ('My first click from the simulation! ');  }); //Simulate user click Behavior$('input'). Trigger ('Click'); //Two methods can be combined$('input'). Click (function () {alert ('My first click from the simulation! '); }). Trigger ('Click'); Sometimes when simulating user behavior, we need to pass parameters to the event, which is similar to theEventadditional data can be numbers, strings, arrays, objects. $('input'). Click (function (E,DATA1,DATA2) {alert (data1+','+data2); }). Trigger ('Click',['ABC','123']);

Note: When a value is passed, it can be passed directly. When the value is above two, it needs to be enclosed in brackets before and after. But it cannot be thought of as an array form, and here is a complex explanation.

$('input'). Click (function (E,DATA1,DATA2) {alert (data1.a+','+data2[1]); }). Trigger ('Click',[{'a':'1','b':'2'},['123','456']]);

In addition to being triggered by a JavaScript event name, it can also be triggered by a custom event, which is actually an arbitrary function that is bound by the. bind ().

$ ('input'). Bind ('myevent', function () {       alert (  ' custom events!  ');   }). Trigger ('myevent');  

The. Trigger () method provides a shorthand scheme that simply calls an empty event of the same name if you want an event to perform a simulated user behavior.

$ ('input'). Click (function () {       alert (' My first click from the simulation!  ');    // empty Click () is performed by Trigger ()  

This convenient method, JQuery almost all of the common events are provided.

JQuery also provides another way to simulate user behavior: The .triggerHandler() use of this method is the same as the. Trigger () method.

$ ('input'). Click (function () {       alert (' My first click from the simulation!  ');   }). Triggerhandler ('click');  

In general usage situations, there is almost no difference between the two, which simulates user behavior or can pass additional parameters. In some special cases, however, the difference arises:
1. .triggerHandler() the method does not trigger the default behavior of the event, but .trigger() it does.

$ ('form'). Trigger ('submit'// impersonate the user to execute the submission, And jump to the execution  page $ ('form'). Triggerhandler ('submit  '// impersonate the user to perform the commit and block the  default behavior

If we want to use. Trigger () to impersonate a user commit and block the default behavior of the event, you need to write this:

$ ('form'). Submit (function (e) {       // block default behavior    }). Trigger ('submit');

2. The .triggerHandler() method affects only the first matching element, and .trigger() affects all.

3. The method returns the .triggerHandler() return value of the current event execution, returns if there is no return value, undefined and .trigger() returns the JQuery object that currently contains the event trigger element (convenient chained concatenating calls).

Alert ($ ('input'). Click (function () {      return  123 ;   }). Triggerhandler ('click'// return 123, no return returned  

4. .trigger() when the event is created, it bubbles. But this bubbling is a custom event, and it's a mechanism for jQuery to extend to the DOM, not DOM features. and .triggerHandler() not bubbling.

var index=1;   $ ('div'). Bind ('myevent', function () {       alert (' custom events '+index);       Index+ +;   });   $ ('. Div3'). Trigger ("myevent");  
Three Event delegate

This method is basically yes. A variant of the bind () method. When you use. bind (), the element that the selector matches is appended with an event handler, and the element that is added later will not. You need to use it again for this purpose. Bind (). For example

<body>  Class="clickme">click here</div></body>  

You can bind this element to a simple click event:

$ ('. ClickMe'). Bind ('click', function () {  Alert ("Bound handler called. "

When you click on an element, a warning box pops up. Then, imagine that another element has been added after this.

$ ('body'). Append ('<div class= "ClickMe" >another target</div>  '

Although this new element can also match the selector ". ClickMe", because this element is added after calling. Bind (), clicking on this element will not have any effect.

. Live () provides a way to respond to this situation. If we were to bind the Click event like this:

$ ('. ClickMe'). Live ('click', function () {  Alert ("Live handler called. " ); });  

Then add a new element:

$ ('body'). Append ('<div class= "ClickMe" >another target</div>  ');  

Then click on the new element and he will still be able to trigger the event handler function.

What is an event delegate? With the reality of the understanding is: There are 100 students at the same time at noon to receive the courier, but the 100 students can not stand at the same time at the school gate, then will entrust the doorman to collect, and then handed over to the students. In JQuery, we use event bubbling to bubble the events of the child's binding to the parent element (or ancestor element), and then the related processing.

If an enterprise application does report processing, the table has 2000 rows, and each row has a button handle. If you use the previous. bind () processing, then you need to bind 2000 events, like 2000 students at the same time standing at the school gate and so on Express, will constantly block the intersection, there will be a variety of accidents. This situation is also the same on the page, which can cause the page to become extremely slow or a direct exception. And, with 2000 buttons using Ajax paging, the. bind () method cannot dynamically bind an element that does not already exist. Like, the new transfer student, The courier cannot verify his identity, may not receive the courier.

//HTML Section<div style="background:red;width:200px;height:200px;"Id="Box"> <input type="Button"Value="Button" class="Button"/> </div>//using. Bind () does not have dynamic binding capabilities, only the original button can be clicked to generate$('. Button'). Bind ('Click', Function () {$ ( This). Clone (). AppendTo ('#box'); }); //use. Live () with dynamic bind function, jQuery1.3 use, jQuery1.7 after discard, jQuery1.9 delete$('. Button'). Live ('Click', Function () {$ ( This). Clone (). AppendTo ('#box');  }); 

The. Live () principle is to bind the click event to the Ancestor element $ (document), and only need to bind to $ (document) once, rather than 2000 times. You can then handle the click events for subsequent dynamically loaded buttons.

When any event is accepted, the $ (document) object checks the event type (Event.type) and the event target (Event.target), and if the click event is a. Button, then executes the handler that was delegated to it: the Live () method has been deleted, cannot be used. If you need to test it, you need to introduce backwards compatible plugins.

// . Live () cannot be called with link concatenating because the attributes of the   parameters cause $ ('#box'). Children (0). Live ('click', function () {       $ (this). Clone (). AppendTo ('#box');    

In the example above, we used a. Clone () clone. In fact, if you want to copy the event behavior, we just need to pass true: .clone(true) . This also enables similar event delegation functions, but the principle is quite different.

One is the replication event behavior, and one is the event delegate. In the case of non-cloning operations, this type of feature can only use event delegates.

$ ('. Button'). Live ('click', function () {       $ ( ' <input type= "button" value= "copied" class= "button"/> '). AppendTo ('#box');   

When we need to stop the event delegate, we can use. Die () to cancel. $ ('. Button '). Die (' click '); Because. Live () and. Die () are deprecated in the jQuery1.4.3 version, followed by a way to clarify the semantics, reduce the level of bubbling propagation, and support link concatenating invocation:. Delegate () and. Undelegate (). However, this method is replaced by the. On () method in the jQuery1.7 version. $ (' #box '). Delegate ('. Button ', ' click ', Function () {$ (this). Clone (). AppendTo (' #box ');}); $ (' #box '). Undelegate ('. Button ', ' click '); Support concatenating call Way $ (' div '). First (). Delegate ('. Button ', ' click ', Function () {$ (this). Clone (). AppendTo (' Div:first ');}); Note: the. Delegate () needs to specify the parent element, then the first parameter is the current element, the second argument is the event mode, and the third argument is the execution function. As with the. bind () method, you can pass additional parameters: the Undelegate () and. Unbind () methods can delete all events directly, such as. undelegate (' click '). You can also delete namespace events, such as. undelegate (' Click.abc '). Note: the. Live () and. Delegate () and. Bind () methods are all event bindings, so the difference is obvious, with two rules in use: 1. When many elements in the DOM bind the same event, 2. When an element binding event is not yet present in the DOM We recommend using the Bind method of the event delegate, otherwise the normal binding of. Bind () is recommended.

JQuery Advanced Events

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.