The On () function of jquery

Source: Internet
Author: User

The on function was added in jquery 1.7
Practical Application Example: http://keleyi.com/a/bjac/scdm44l9.htm

Description: Bind one or more event handlers to the selected element.

Defined:
. On (events [, selector] [, data], handler (EventObject))

Parameters:
Events
Type: String
One or more space-delimited event types and optional namespaces, or just namespaces, such as "click", "Keydown.myplugin", or ". Myplugin".

Selector
Type: String
A selector string that is used to filter out the descendant elements in the selected element that can trigger events. If the selector is null or if the selector is omitted, the selected element will always trigger the event.

Data
Type: anything
The event.data to pass to the event handler when an event is triggered.

Handler (EventObject)
Type: Function ()
The function that is executed when the event is triggered. If the function simply executes return false, the position of the parameter can be shortened directly to false.

Defined:
. On (events [, selector] [, data])

Events
Type: Plainobject
An object whose key is one or more event types separated by spaces and an optional namespace, and the value is the event handler for these event types.

Selector
Type: String
A selector string that is used to filter out the descendant elements in the selected element that can trigger events. If the selector is null or if the selector is omitted, the selected element will always trigger the event.

Data
Type: anything
The event.data to pass to the event handler when an event is triggered.



The. On () method event handler to the element in the currently selected jquery object. In jquery 1.7, the. On () method provides all the functionality for binding event handling. To help convert from the old jquery event method, view. Bind (),. Delegate (), and. Live (). To remove the. On () bound events, see. Off (). To bind an event and run it only once, and then delete yourself, see. One ()

Reference:
Http://keleyi.com/a/bjad/n828yb7w.htm
Http://keleyi.com/a/bjac/bg0m15bi.htm


Event names and namespaces (incident name and namespace)

The name of any event can be used as the events parameter. jquery will pass the standard JavaScript event type for all browsers, and when the user operates an event such as Click, the browser invokes the function of the handler parameter. Additionally, 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" defines two namespace Myplugin and simple for the Click event. The Click event handler, which is bound by the above method, can be removed by using. Off ("Click.myplugin") or. Off ("Click.simple") to remove the Click event handler bound to the corresponding element without interfering with other bindings on that element. Click (click) "Event. 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 second use of the. On () method, the events parameter is a JavaScript object or a key-value pair. The key is equivalent to the events parameter, a space-delimited string of event names, and an optional namespace. The value of each key is a function (or a value of false), which is equivalent to the 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.

Direct and delegated events (directly and delegate event)

Most browser events bubble, or propagate, from the inside out, beginning with the element at the very deepest of the document (the event target), passing it all the way to the body and document elements. (Fool's Wharf Note: Event bubbling simply means that these types of events are triggered on all elements of the bubbling path that are bound to the same event type. In Internet Explorer 8 and lower, some events, such as the change and submit itself, do not bubble, but jquery simulates the bubbling behavior on these events for cross-browser consistency.

If selector is omitted or null, then the event handler is referred to as a direct event or a direct binding event. Each time a selected element triggers an event, the handler executes, whether it is directly bound to the element or bubbled from the descendant (inner) element to the element's

When the selector parameter is provided, the event handler refers to the delegate event (Fool's Wharf Note: There are often many people calling it agent events). The event does not fire on the directly bound element, but the event handler is triggered when the selector parameter selector matches the descendant (inner element). JQuery starts bubbling from the event target to the upper element (for example, from the outermost element to the outermost element), and the events on the propagation path that are bound to the same events will be triggered if they satisfy the matching selectors.

Event handling can only be bound to the currently selected element, and when your code calls. On (), they must already exist in the page document. To ensure that the current element can be selected (Fool's Wharf Note: that is, present), it is best to do event binding in the Ready event of document. If the new HTML is injected into the page, the event is bound to the element that matches the selector (selector parameter) when the new HTML is placed on the page. Or, use the delegate event binding event handler, as described below.

Delegate events have an advantage that they can handle these events after the descendant elements are added to the document. When you make sure that the selected element already exists, you can use the delegated event to avoid frequent binding events and Unbinding events when event binding occurs. For example, this element that already exists can be a container element of view in the Model-view-controller (model-View-Controller) mode, or document. If you want to monitor the bubbling events in all documents. The document element is valid in the head before any other HTML is loaded, so you can safely do event binding in the head without waiting for the document to load.

In addition to binding events to non-created descendant elements (that is, the advantages mentioned above), another benefit of agent events is that the agent event is less expensive when you need to monitor many elements. For example, there are 1,000 rows in the tbody of a table, and the following example binds events for these 1,000 elements:

$ ("#dataTable tbody tr"). On ("click", Function (event) {
Alert (This). text ());
});
The method of delegating an event is only one element of the event handler, Tbody, and the event will only bubble up one layer (from the clicked TR to tbody):

$ ("#dataTable tbody"). On ("click", "TR", function (event) {
Alert (This). text ());
});
Note: Delegate events cannot be used with SVG.

The event handler and its environment (events handler and its environment)

The handler parameter must be a function (or false value, see below) unless you pass an object to the events parameter. You can provide an anonymous handler for the. On () call, as in the example above, or you can declare a function and then use the function name as an argument:

function Notify () {alert ("clicked");}
$ ("button"). On ("click", notify);
When the browser triggers an event or other JavaScript call to the jquery. Trigger () method, jquery passes an event object to this handler, which can be used to parse and change the state of the events. This object is provided by the browser to provide a labeled subset of the data, you need the browser's own unmodified original event object, you can use Event.originalevent to get. For example, Event.type contains the name of the event (for example, "resize") and event.target represents the deepest element of the event (the most inner layer).

By default, most events start bubbling from the original event target (the target element) until the document element. Each element is along this path at the DOM level, and jquery invokes any matching bound event handlers. A handler can call the Event.stoppropagation () to prevent the event from bubbling up the document tree (thus preventing the handlers of these elements from running). Any other handlers that are bound to the current element will run, and in order to prevent this, you can call Event.stopimmediatepropagation (). (The events that are bound on elements are called in the same order as they are bound.) )

Similarly, a handler can call the Event.preventdefault () to cancel the browser default action behavior; For example, there is a default click event on a link. Not all of the default actions for browser events, not all default actions can be canceled. For more information, see the Events specification

Calling Event.stoppropagation () and Event.preventdefault () will automatically return false from an event handler. You can also directly use false as the handler parameter, as a shorthand for function () {return false;}. Therefore, the following wording is $ ("a.disabled"). On ("click", False); All links that contain the "disabled" style will be blocked from the default behavior, and the bubbling behavior on the event is blocked.

When calling handlers for jquery, the This keyword points to the element that is currently executing the event. For direct events, this represents the element that binds the event. For agent events, this represents the element that matches the selector. (Note that if the event is bubbling from a descendant element, then this may not be equal to event.target.) To use the related methods of jquery, you can create a jquery object based on the current element, that is, use $ (this).

Passing data to the handler (passing the information to the handler)

If the data parameter gives. On () and is not null or undefined, the event.data is passed to the handler each time the event is triggered. The data parameter can be of any type, but if it is a string type, then the selector parameter must provide, or explicitly pass NULL, such that the data parameter is not mistaken for a selector. It is best to use an object (a key-value pair), so you can pass multiple values as attributes.

jquery 1.4, the same event handler can be bound to an element multiple times. This is especially useful for using the Event.data feature, or for using unique data in closures. For example:

function greet (event) {alert ("Hello" +event.data.name);}
$ ("button"). On ("click", {name: "Karl"}, greet);
$ ("button"). On ("click", {name: "Addy"}, greet);
When you click the button, the code above generates two different alarms.

In addition to passing in the data parameter to the. On () method, you can also pass in the parameter to. Trigger () or. Triggerhandler ().

Event Performance (incident performance)

In most cases, an event such as Click rarely occurs, and performance is not explicitly indicated. However, high-frequency events such as MouseMove or scroll can trigger dozens of times per second, in which case it becomes more important to use the event wisely. You can improve the performance of events as follows: Reduce the amount of work in event handlers, cache the information you want to use in the event handler, and not recalculate it again, or use settimeout to limit the actual number of page updates.

Many delegated event handlers are bound to the top level of the document tree, which can degrade performance. Each time an event occurs, JQuery needs to compare all events of that type from the start of the event target (the target element) to each element on the path at the top of the document. For better performance, when binding agent events, the bound element is best to be as close to the target element as possible. Avoid adding agent events on document or Document.body in large documents.

jquery can very quickly handle tag#id.class forms of simple selectors when they are used to filter delegated events. So "#myForm", "a.external", and "button" are all quick selectors. If the proxy event selector uses overly complex forms, especially if a hierarchical selector is used, though this can greatly degrade performance, it is still fast enough for most applications. It is easy to avoid the use of hierarchical selectors by finding a way to bind events to more appropriate elements. For example, use $ ("#commentForm"). On ("click", ". AddNew", addcomment) instead of $ ("body"). On ("click", "#commentForm. AddNew", AddComment).

Additional notes (Other considerations)

Some shorthand methods for events such as. Click () can be used to attach or trigger event handlers. For a complete list of shorthand methods, see Events Category

Although not recommended, the pseudo-class event name "Hover" can be used as an abbreviation for "MouseEnter MouseLeave". Do not confuse with the. Hover () method that accepts two functions, where only one handler is bound to the pseudo-class event name "hover"; the handler should check the Event.type to determine whether it is a MouseEnter or MouseLeave event.

The jquery Event system requires a DOM element to append data through the attributes of the element, so that events can be tracked and passed. Object, embed, and applet elements cannot bind data, so there is no event binding for jquery.

The consortium specifies that the focus and blur events are not bubbling, but jquery defines cross-browser focusin and Focusout events and can bubble. When focus and blur bind delegated event handlers, jquery parses the names and provides them to pay Focusin and focusout separately. To maintain consistency and clarity, use the name of the bubbling event type.

In all browsers, load, scroll, and error events (for example, on a element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble, such events are not supported for delegation use, but can be used if the event handler is directly bound on the element that generated the event.

The Error event on the Window object uses nonstandard parameters and return value conventions, so jquery does not support this event. As an alternative, assign a handler function directly with the Window.onerror property.

Example:

Example: When you click a paragraph, the text in that paragraph is displayed:
$ ("P"). On ("click", Function () {
Alert (This). text ());
});

Example: Pass in the data to the event handler and get the incoming data by name in the event handler function:
function MyHandler (event) {
alert (Event.data.foo);
}
$ ("P"). On ("click", {foo: "Bar"}, MyHandler)

Example: Cancels the form's commit action and prevents the event from bubbling by returning false:
$ ("form"). On ("Submit", false)

Example: Cancels only the default action by using. Preventdefault ().
$ ("form"). On ("Submit", function (event) {
Event.preventdefault ();
});

Example: Prevents the bubbling behavior of the commit event by using. Stoppropagation (), but does not prohibit the commit behavior.
$ ("form"). On ("Submit", function (event) {
Event.stoppropagation ();
});


Example: Add and Trigger custom events (non-browser events).
<! DOCTYPE html>
<style>
p {color:red;}
span {color:blue;}
</style>
<script type= "Text/javascript" src= "Http://keleyi.com/keleyi/pmedia/jquery/jquery-1.10.2.min.js" ></ Script>
<body>
<p>has an attached custom event.</p>
<button>trigger Custom Event</button>
<span style= "Display:none;" ></span>
<script>
$ ("P"). On ("Mycustomevent", Function (E, myName, myvalue) {
$ (this). Text (MyName + ", Hi there!");
$ ("span"). Stop (). CSS ("opacity", 1)
. Text ("MyName =" + myName)
. FadeIn (+). FadeOut (1000);
});
$ ("button"). Click (function () {
$ ("P"). Trigger ("Mycustomevent", ["John"]);
});
</script>

</body>

Example: Use an object to add multiple event handlers at the same time.
<! DOCTYPE html>
<style>
. Test {color: #000; padding:. 5em; border:1px solid #444;}
. Active {color: #900;}
. Inside {}
</style>
<script src= "Http://code.jquery.com/jquery-latest.js" ></script>
<body>
<div class= "Test" >test div</div>
<script>$ ("Div.test"). On ({
Click:function () {
$ (this). Toggleclass ("active");
},
Mouseenter:function () {
$ (this). AddClass ("Inside");
},
Mouseleave:function () {
$ (this). Removeclass ("Inside");
}
});</script>

</body>


Example: When you click on any paragraph, a paragraph is appended to it. Note that. On () adds an event to any paragraph, including the newly generated paragraph, because the bound event is triggered when the event bubbles onto the body element that already exists.
<! DOCTYPE html>
<style>
p {background:yellow; font-weight:bold; cursor:pointer;
padding:5px; }
p.over {background: #ccc;}
span {color:red;}
</style>
<script src= "Http://code.jquery.com/jquery-latest.js" ></script>
<body>
<p>click me!</p>
<span></span>
<script>
var count = 0;
$ ("Body"). On ("click", "P", function () {
$ (this). After ("<p>another paragraph!" + (++count) + "</p>");
});
</script>

</body>

Example: When you click a paragraph, the text in that paragraph is displayed:
$ ("Body"). On ("click", "P", function () {
Alert (This). text ());
});

Example: Use the Preventdefault method to unlink the default action.
$ ("Body"). On ("Click", "a", function (event) {
Event.preventdefault ();
});

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.