The
on() function is used to bind theevent processingfunction to one or more events of the specified element.
In addition, you can also pass some additional required data to the event handling function.
Starting from jQuery 1.7, the on() function provides all the functions required to bind event handlers, and is used to uniformly replace the previous event functions such as bind(), delegate(), live(), etc.
on() supports binding events directly on the target element, and also supports delegated binding on the ancestor elements of the target element. In event delegation binding mode, even if it is a newly added element after executing the on() function, as long as it meets the conditions, the bound event handling function will be effective for it.
In addition, this function can bind multiple event processing functions to the same element and the same event type. When an event is triggered, jQuery will execute the bound event processing functions in the order of binding.
To delete an event bound through on(), use the off() function. If you want to attach an event, execute it only once, and then delete itself, use the one() function.
This function belongs to the jQuery object (instance).
Syntax
jQuery 1.7 Added this function. It mainly has the following two forms of usage:
Usage one:
jQueryObject.on( events [, selector ] [, data ], handler )
Usage two:
jQueryObject.on( eventsMap [, selector ] [, data ] )
Parameters
Parameter Description
events String type one or more with spaces Separated event types and optionalnamespaces, such as "click", "focus click", "keydown.myPlugin".
eventsMap Object type is anObject object, each attribute corresponds to the event type and optional namespace (parameter events), and the attribute value corresponds to the bound event processing function (parameter handler) .
selector Optional/String type A jQuery selector used to specify which descendant elements can trigger bound events. If this parameter is null or omitted, it means that the current element itself is bound to the event (the actual triggerer may also be a descendant element, as long as the event stream can reach the current element).
data Optional/Any type of data that needs to be passed to the event processing function through event.data when an event is triggered.
The event processing function specified by the handler Function type.
For the optional namespace in the parameter events, please refer to the sample code below.
Regarding the parameter selector, you can simply understand it as: if the parameter is equal to null or omitted, the event is bound to the current matching element; otherwise, it is the descendant element of the current matching element that matches the selector selector. Element binding event.
This in the parameter handler points to the DOM element that triggers the event among the descendant elements of the current matching element. If the selector parameter is null or omitted, this points to the current matching element (that is, the element).
on() will also pass in a parameter for the handler: the Event object representing the current event.
The return value of the parameter handler has the same effect as the return value of the DOM native event processing function. For example, the event handler function of the "submit" (form submission) event returns false, which can prevent the form from being submitted.
If the event processing function handler only returns a false value, you can directly set the handler to false.
Return value
on()The return value of the functionis of jQuery type and returns the current jQuery object itself.
Important note:
If the selector parameter is passed, the on() function does not bind event handlers to elements matching the current jQuery object, but to their descendant elements that match The element binding event handler of the selector parameter of the selector. The on() function does not directly bind events to these descendant elements one by one, but delegates processing to the matching elements of the current jQuery object. Due to the DOM level 2 event flow mechanism, when the descendant element selector triggers an event, the event will be passed to all its ancestor elements in the event bubbling. When the event flow is passed to the current matching element, jQuery will determine which descendant element it is. When an event is triggered, if the element matches the selector, jQuery will capture the event and execute the bound event handler.
In layman's terms, if we want to bind click event handlers to all
tags on the page, we can directly bind click event handlers to each P tag separately. For example:
// Bind the click event handler function handler to all P elements respectively
$("p").on("click", handler);
We can also bind the event delegation mechanism to any common ancestor element of these P tags and use the event bubbling mechanism of the DOM to unify delegation processing. When we trigger the click event of an element, JS will notify the element and its "parent" element, "grandfather" element... until the document object at the top. If these elements have click event handlers bound to them, will be executed in sequence.
// Bind the click event handler function handler to the body element. If the click event is triggered by its descendant P element, handler
will be executed.$(document.body).on("click", "p", handler);
在这里的示例中,事件委托机制就是,我们不为每个P元素直接绑定click事件处理函数,而是委托给其某个公共的祖辈元素(此处示例中为document.body),"告诉"他:如果接收到了click事件触发通知,并且这个click事件是由我们这些P元素其中之一触发的,就执行祖辈元素上委托绑定的事件处理函数。
注意:"focus"、"blur"等部分事件不支持冒泡,使用事件委托机制将无效。不过,他们一般也有对应的支持冒泡的事件。例如与"focus"对应的"focusin",与"blur"对应的"focusout"。此外,我们也可以使用event.stopPropagation()方法,让当前触发的事件停止冒泡。
示例&说明
以点击事件("click")为例,以下是jQuery中事件函数的常规用法(某些函数也存在其它形式的用法,此处暂不列出):
// 这里的选择器selector用于指定可以触发事件的元素
// 这里的选择器ancestor应是selector的祖辈元素,selector触发的事件可以被其祖辈元素在事件流中捕获,从而以"代理"的形式触发事件。
// jQuery 1.0+ (1.4.3+支持参数data)
$("selector").click( [ data ,] handler );
// jQuery 1.0+ (1.4.3+支持参数data)
$("selector").bind( "click" [, data ], handler );
// jQuery 1.3+ (1.4+支持参数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 );
请参考下面这段初始HTML代码:
CodePlayer
专注于编程开发技术分享
http://www.365mini.com
We bind click events to all
elements in
// Bind click event handlers to all p elements in the div
// Only n2 and n3 can trigger this event
$("div").on(" click", "p", function(){
// This here points to the p element (Element) that triggered the click event
alert( $(this).text() );
});
Run the code (please copy other codes to the demo page to run)
If you want to bind all
elements, you can write as follows jQuery code:
//Bind click event handlers for all p elements (note: the selector parameter is omitted here)
//n2, n3, n5 can trigger this event
$("p").on("click", function(event){
// This here points to the p element (Element) that triggered the click event
alert ( $(this).text() );
});
In addition, we can also bind multiple events at the same time and pass some additional data to the event handling function. We It can be processed through the parameter event (Event event object) passed in by jQuery for the event processing function:
var data = { id: 5, name: "Zhang San" };
/ / Bind two mouseenter mouseleave events to n5 and pass in additional data data
// The additional data can be of any type
$("body").on("mouseenter mouseleave", "#n5", data, function(event){
var $me = $(this);
var options = event.data; // This is what is passed in Additional data
if( event.type == "mouseenter"){
$me.html( "Hello," + options.name + "!");
}else if(event.type == "mouseleave" ){
$me.html( "Goodbye!");
});
In addition, even if the qualifying element is newly added after the on() function is executed, the binding event is still valid for it. Taking the initial HTML code as an example, we can write the following jQuery code:
// Bind click event handlers to all p elements in the div
// Only n2 and n3 can be triggered The event
$("div").on("click", "p", function(event){
alert( $(this).text() );
});
// The n6 added later can also trigger the above click event, because it is also the p element in the div
$("#n1").append( '
The click event bound above also takes effect on this element!
');Parameter events also supports additional namespaces for event types. When binding multiple event handlers of the same type to the same element. Using namespaces, you can limit the scope of triggering or removal when triggering events andremoving events.
function clickHandler(event){ alert( "触发时的命名空间:[" + event.namespace + "]"); } var $p = $("p"); // A:为所有p元素绑定click事件,定义在foo和bar两个命名空间下 $p.on( "click.foo.bar", clickHandler ); // B:为所有p元素绑定click事件,定义在test命名空间下 $p.on( "click.test", clickHandler ); var $n2 = $("#n2"); // 触发所有click事件 $n2.trigger("click"); // 触发A和B (event.namespace = "") // 触发定义在foo命名空间下的click事件 $n2.trigger("click.foo"); // 触发A (event.namespace = "foo") // 触发定义在bar命名空间下的click事件 $n2.trigger("click.bar"); // 触发A (event.namespace = "bar") // 触发同时定义在foo和bar两个命名空间下的click事件 $n2.trigger("click.foo.bar"); // 触发A (event.namespace = "bar.foo") // 触发定义在test命名空间下的click事件 $n2.trigger("click.test"); // 触发B (event.namespace = "test") // 移除所有p元素定义在foo命名空间下的click事件处理函数 $p.off( "click.foo" ); // 移除A
on()Parameters of the functioneventsMap is an object that can specify multiple "event types-processing functions" in the form of "property-value". The corresponding sample code is as follows:
var data = { id: 5, name: "张三" }; var events = { "mouseenter": function(event){ $(this).html( "你好," + event.data.name + "!"); }, "mouseleave": function(event){ $(this).html( "再见!"); } }; //为n5绑定mouseenter mouseleave两个事件,并为其传入附加数据data $("body").on(events, "#n5", data);
The above is the detailed content of Detailed explanation of jQuery.on() function usage examples. For more information, please follow other related articles on the PHP Chinese website!