search
HomeWeb Front-endJS TutorialDetailed explanation of how to use jQuery.delegate() function

Detailed explanation of how to use jQuery.delegate() function

Jun 26, 2017 am 10:49 AM
InstructionsfunctionDetailed explanation

delegate() The function is used to bind one or more events for the specified element Event processing function .

In addition, you can also pass some additional required data to the event handling function.

Even if it is a newly added element after executing the delegate() function, as long as it meets the conditions, the bound event handling function is still valid 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 delegate(), use the undelegate() function.

Starting from jQuery 1.7, please use the event function on() instead of this function.

This function belongs to the jQuery object (instance).

Syntax

jQuery

1.4.2 Add this function. It mainly has the following two forms of usage:

Usage one

jQueryObject.delegate( selector , events [, data ], handler )

Usage two:jQuery 1.4. 3 Added support for this usage.

jQueryObject.delegate( selector, eventsMap )

Parameters

ParametersDescriptionselectoreventsdatahandlereventsMap

关于参数events中可选的命名空间,请参考最下面的示例代码。

关于参数selector,你可以简单地理解为:如果该参数等于null或被省略,则为当前匹配元素绑定事件;否则就是为当前匹配元素的后代元素中符合selector选择器的元素绑定事件。

参数handler中的this指向当前匹配元素的后代元素中触发该事件的DOM元素。如果参数selector等于null或被省略,则this指向当前匹配元素(也就是该元素)。

delegate()还会为handler传入一个参数:表示当前事件的Event对象。

参数handler的返回值与DOM原生事件的处理函数返回值作用一致。例如"submit"(表单提交)事件的事件处理函数返回false,可以阻止表单的提交。

如果事件处理函数handler仅仅只用于返回false值,可以直接将handler设为false。

返回值

delegate()函数的返回值jQuery类型,返回当前jQuery对象本身。

重要说明delegate()函数并不是为当前jQuery对象匹配的元素绑定事件处理函数,而是为它们的后代元素中符合选择器selector参数的元素绑定事件处理函数。delegate()函数并不是直接为这些后代元素挨个绑定事件,而是"委托"给当前jQuery对象的匹配元素来处理。由于DOM 2级的事件流机制,当后代元素selector触发事件时,该事件会在事件冒泡中传递给其所有的祖辈元素,当事件流传递到当前匹配元素时,jQuery会判断是哪个后代元素触发了事件,如果该元素符合选择器selector,jQuery就会捕获该事件,从而执行绑定的事件处理函数。

示例&说明

以点击事件("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代码:

<p id="n1">
    <p id="n2"><span>CodePlayer</span></p>
    <p id="n3"><span>专注于编程开发技术分享</span></p>
    <em id="n4">http://www.365mini.com</em>
</p>
<p id="n5">Google</p>

我们为

中的所有

元素绑定点击事件:

// 为p中的所有p元素绑定click事件处理程序
// 只有n2、n3可以触发该事件
$("p").delegate("p", "click", function(){
    // 这里的this指向触发点击事件的p元素(Element)
    alert( $(this).text() );
});

运行代码(其他代码请自行复制到演示页面运行)

如果要绑定所有的

元素,你可以编写如下jQuery代码:

//为所有p元素绑定click事件处理程序(body内的所有p元素,就包含所有的p元素)
//n2、n3、n5均可触发该事件
$("body").delegate("p", "click", function(event){
// 这里的this指向触发点击事件的p元素(Element)
    alert( $(this).text() );
});

此外,我们还可以同时绑定多个事件,并为事件处理函数传递一些附加的数据,我们可以通过jQuery为事件处理函数传入的参数event(Event事件对象)来进行处理:

var data = { id: 5, name: "李四" };

//为n5绑定mouseenter mouseleave两个事件,并为其传入附加数据data
//附加数据可以是任意类型
$("body").delegate("#n5", "mouseenter mouseleave", 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( "再见," + options.name + "!");      
    }           
} );

此外,即使符合条件的元素是delegate()函数执行后新添加,绑定事件对其依然有效。同样以初始HTML代码为例,我们可以编写如下jQuery代码:

//为p中的所有p元素绑定click事件处理程序
//只有n2、n3可以触发该事件
$("p").delegate("p", "click", function(event){
    alert( $(this).text() );
});

//后添加的n6也可以触发上述click事件,因为它也是p中的p元素
$("#n1").append(&#39;<p id="n6">上述绑定的click事件对此元素也生效!</p>&#39;);

参数events还支持为事件类型附加额外的命名空间。当为同一元素绑定多个相同类型的事件处理函数时。使用命名空间,可以在触发事件、移除事件时限定触发或移除的范围。

function clickHandler(event){
    alert( "触发时的命名空间:[" + event.namespace + "]");
}

var $p = $("p");

// A:为所有p元素绑定click事件,定义在foo和bar两个命名空间下
$("body").delegate( "p", "click.foo.bar", clickHandler );

// B:为所有p元素绑定click事件,定义在test命名空间下
$("body").delegate( "p", "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.undelegate( "click.foo" ); // 移除A

delegate()函数的参数eventsMap是一个对象,可以"属性-值"的方式指定多个"事件类型-处理函数"。对应的示例代码如下:

var events = {
    "mouseenter": function(event){
        $(this).html( "你好!");       
    },

    "mouseleave": function(event){
        $(this).html( "再见!");
    }
};

//为n5绑定mouseenter mouseleave两个事件,并为其传入附加数据data
$("body").delegate("#n5", events);


String type is 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).
String type One or more event types separated by spaces and an optional namespace, For example "click", "focus click", "keydown.myPlugin".
Optional/any type When an event is triggered, any data needs to be passed to the event processing function through event.data.
The event handler function specified by the Functidelegate type.
Object type is an Object object, each of its properties corresponds to the event type and optional namespace (parameter events), the attribute value corresponds to the bound event processing function (parameter handler).

The above is the detailed content of Detailed explanation of how to use jQuery.delegate() function. 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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

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.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor