search
HomeWeb Front-endJS TutorialDetailed explanation of jQuery.on() function usage examples

Detailed explanation of jQuery.on() function usage examples

Jun 30, 2017 pm 01:51 PM
ExampleDetailed explanation

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 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 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

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

Google

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 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()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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!