jquery Event---Advanced events

Source: Internet
Author: User

Content outline:

1. Analog operation

2. Namespaces

3. Event Delegation

4.on, off and one

The publication is not easy, reproduced please indicate the source!

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 the extra data with Event.data (but note the difference, see the basic event chapter), which can be numbers, strings, arrays, objects.

$ (' input '). Click (Function (E, data1, data2) {

Alert (data1 + ', ' + data2);

}). Trigger (' Click ', [' abc ', ' 123 ');

PS: 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 not as an array form, here is a complex description:

$ (' 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 the JavaScript event name, it can also be used for custom event triggering, so-called custom events are actually an arbitrary function that is bound by the. bind (). custom events cannot be performed individually, but can be performed by trigger impersonation. examples are as follows:

$ (' input '). Bind (' myevent ', function () {

Alert (' Custom event! ‘);

}). 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! ‘);

}). Click (); Execute empty click () to impersonate user behavior

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

JQuery also provides another way to simulate user behavior:. Triggerhandler (); The 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 from trigger (), which is to simulate user behavior or to pass additional parameters. However, in some special cases there are still differences, mainly the following four points:

1. The. Triggerhandler () method does not trigger the default behavior of the event, while. Trigger () will.

$ (' form '). Trigger (' submit '); Impersonate the user to execute the submission and jump to the execution page

$ (' form '). Triggerhandler (' submit '); Impersonate a user to perform a 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) {

  E.preventdefault (); Block default behavior

}). Trigger (' submit ');

2. The. Triggerhandler () method affects only the first matched element, and. Trigger () affects all.

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

Alert ($ (' input '). "Click (function () {

return 123;

}). Triggerhandler (' click ')); //Return 123, no return returned undefined

4.. trigger () Bubbles when the event is created. But this bubbling is a custom event, and it's a mechanism for jquery to extend to the DOM, not DOM features. and. Triggerhandler () does not bubble.

Example:

HTML part of the code:

1 <Divclass= "D1">2 3          <Divclass= "D2">4 5                    <Divclass= "D3">6 7 Div8 9                    </Div>Ten  One          </Div> A  - </Div>

JS Code section:

1$ (' div '). bind (' MyEvent ',function () {2 3Alert (' Custom event! ‘);4 5 })6 7 8$ ('. D3 '). Trigger (' myevent ');//will bubble, with 3 outputs9 Ten  One$ (' div '). bind (' MyEvent ',function () { A  -Alert (' Custom event! ‘); -  the }) -   -  -$ ('. D3 '). Triggerhandler (' MyEvent ');//not bubbling, only 1 outputs

Two Name space

Sometimes, we want to remove the event. However, it is often troublesome to remove an event with the same name as an element binding, which can be resolved using the event's namespace.

$ (' input '). Bind (' click '). ABC', function () {

Alert (' abc ');

});

$ (' input '). Bind (' click '). xyz', function () {

Alert (' xyz ');

});

$ (' input '). Unbind (' click.abc '); To remove the Click event named ABC

PS: You can also use ('. ABC ') directly, so that you can remove different events from the same namespace. For analog operations. Trigger () and. Triggerhandler (), the usage is the same.

$ (' input '). Trigger (' click.abc ');

Three Event delegate

//html Code Section

1 <Divstyle= "background:red;width:200px;height:200px;"ID= "box">2     <inputtype= "button"value= "button"class= "button" />3 </Div>4 5  

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 ps:.live () principle is to bind the click event to the Ancestor element $ (document), rather than multiple times, by binding only one time to $ (document). You can then handle the click events for subsequent dynamically loaded buttons. When any event is accepted, the$ (document) object examines the event type (event.type) and the event target (event.target), if The Click event is a. button, then the handler that is delegated to it is executed. After version 1.9. The live () method has been deleted and cannot be used. If you need to test it, you need to introduce backwards compatible plugins.

//.live () cannot use link concatenating call because the attribute of the parameter causes

$ (' #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. As follows:

$ ('. Button '). Live (' click ', function () {

$ (' <input type= ' button "value=" Copy of "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 concatenating invocation:. Delegate () and. Undelegate (). However, this method is replaced by the. On () method in the jQuery1.7 version.

$ (' #box '). Delegate ('. Button ', ' click ', function () {//Note the order of the elements and parameters bound

$ (this). Clone (). AppendTo (' #box ');

});

$ (' #box '). Undelegate ('. Button ', ' click ');

Support for concatenating invocation mode

$ (' div '). First (). Delegate ('. Button ', ' click ', function () {

$ (this). Clone (). AppendTo (' Div:first ');

});

Ps:.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 ').

The Ps:.live () and the. 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 that is about to be generated We recommend using the Bind method of the event delegate, otherwise the normal binding of. Bind () is recommended.

Four. on, off, and One

There are currently three groups of six methods for binding events and bindings. Since the coexistence of these three groups can cause some confusion, the jQuery1.7 version is released later. The On () and. Off () methods completely discard the previous three groups.

Override. Bind () mode

$ ('. Button '). On (' click ', function () {

Alert (' Replace. bind () ');

});

Override. Bind () mode and use additional data and event objects

$ ('. Button '). On (' click ', {User: ' Lee '}, function (e) {

Alert (' Alternative. bind () ' + e.data.user);

});

Override. Bind () mode, and bind multiple events

$ ('. Button '). On (' mouseover mouseout ', function () {

Alert (' Replace. bind () move in and out! ‘);

});

Override. Bind () mode to bind multiple events in an object pattern

$ ('. Button '). On ({

Mouseover:function () {

Alert (' Replace. bind () move in! ‘);

},

Mouseout:function () {

Alert (' Replace. bind () move out! ‘);

}

});

Override. Bind () to block default behavior and cancel bubbling

$ (' form '). On (' Submit ', function () {

return false;

});

Or

$ (' form '). On (' Submit ', false); Pass false parameter directly

Override. Bind () mode to block default behavior

$ (' form '). On (' Submit ', function (e) {

E.preventdefault ();

});

Override. Bind () mode to cancel bubbling

$ (' form '). On (' Submit ', function (e) {

E.stoppropagation ();

});

Override. Unbind () mode, remove event

$ ('. Button '). Off (' click ');

$ ('. Button '). Off (' click ', FN);

$ ('. Button '). Off (' click.abc ');

Replace. Live () and. Delegate (), event delegates

$ (' #box '). On (' click ', '. Button ', function () {

$ (this). Clone (). AppendTo (' #box ');

});

Override. Die () and. Undelegate (), cancel event delegation

$ (' #box '). Off (' click ', '. Button ');

Note: As in the previous way, event delegation and cancellation event delegates also have various collocation methods, such as extra data, namespaces, etc., which are not mentioned here.

Whether it's. bind () or. On (), the event is not automatically removed after the binding event and needs to be removed manually by. Unbind () and. Off (). JQuery provides the. One () method, which automatically removes events after the binding element has finished executing, and can be used to trigger events only once.

Similar to. bind () triggers only once

$ ('. Button '). One (' click ', function () {

Alert (' One triggers only once! ‘);

});

Similar to. Delegate () triggers only once

$ (' #box). One ('. Button ', ' click ', function () {

Alert (' One triggers only once! ‘);

});

For my lover,

And thank you mr.lee!

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.