Home > Article > Web Front-end > Detailed explanation of jQuery.on() function usage examples
The
on() function is used to bind the event processing function 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 optional namespaces, such as "click", "focus click", "keydown.myPlugin".
eventsMap Object type is an Object object, each of its attributes 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 of the "submit" (form submission) event returns false to 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 function is 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 64e5601d0a941f4972a2954192bdae18 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 top document object. 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
$(document.body) will be executed. on("click", "p", handler);
In the example here, the event delegation mechanism is that we do not directly bind the click event handler to each P element, but delegate it to one of its public ancestor elements (document.body in this example) , "tell" him: If a click event trigger notification is received, and the click event is triggered by one of our P elements, the event handler bound to the delegate on the ancestor element will be executed.
Note: Some events such as "focus" and "blur" do not support bubbling, and using the event delegation mechanism will be invalid. However, they generally also have corresponding events that support bubbling. For example, "focusin" corresponds to "focus", and "focusout" corresponds to "blur". In addition, we can also use the event.stopPropagation() method to stop the currently triggered event from bubbling.
Example & Description
Taking the click event ("click") as an example, the following is the general usage of event functions in jQuery (some functions also have other forms of usage, which are not discussed here for the time being. List):
// 这里的选择器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 );
Please refer to the following initial HTML code:
<div id="n1"> <p id="n2"><span>CodePlayer</span></p> <p id="n3"><span>专注于编程开发技术分享</span></p> <em id="n4">http://www.365mini.com</em> </div> <p id="n5">Google</p>
We bind click events to all e388a4556c0f65e1904146cc1a846bee elements in dc6dce4a544fdca2df29d5ac0ea9906b:
// 为div中的所有p元素绑定click事件处理程序 // 只有n2、n3可以触发该事件 $("div").on("click", "p", function(){ // 这里的this指向触发点击事件的p元素(Element) alert( $(this).text() ); });
If you want to bind all e388a4556c0f65e1904146cc1a846bee elements, you can write the following jQuery code:
//为所有p元素绑定click事件处理程序(注意:这里省略了selector参数) //n2、n3、n5均可触发该事件 $("p").on("click", function(event){ // 这里的this指向触发点击事件的p元素(Element) alert( $(this).text() ); });
In addition, we can also bind multiple events at the same time and pass some additional Data can be processed through the parameter event (Event event object) passed in by jQuery for the event processing function:
var data = { id: 5, name: "张三" }; // 为n5绑定mouseenter mouseleave两个事件,并为其传入附加数据data // 附加数据可以是任意类型 $("body").on("mouseenter mouseleave", "#n5", data, function(event){ var $me = $(this); var options = event.data; // 这就是传入的附加数据 if( event.type == "mouseenter"){ $me.html( "你好," + options.name + "!"); }else if(event.type == "mouseleave" ){ $me.html( "再见!"); } }); 此外,即使符合条件的元素是on()函数执行后新添加,绑定事件对其依然有效。同样以初始HTML代码为例,我们可以编写如下jQuery代码: // 为div中的所有p元素绑定click事件处理程序 // 只有n2、n3可以触发该事件 $("div").on("click", "p", function(event){ alert( $(this).text() ); }); // 后添加的n6也可以触发上述click事件,因为它也是div中的p元素 $("#n1").append('<p id="n6">上述绑定的click事件对此元素也生效!</p>');
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 and removing 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()函数的参数eventsMap是一个对象,可以"属性-值"的方式指定多个"事件类型-处理函数"。对应的示例代码如下: 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!