Home > Web Front-end > JS Tutorial > body text

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

黄舟
Release: 2017-06-26 10:49:14
Original
1639 people have browsed it

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 )
Copy after login

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

jQueryObject.delegate( selector, eventsMap )
Copy after login

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 );
Copy after login

请参考下面这段初始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>
Copy after login

我们为

中的所有

元素绑定点击事件:

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

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

如果要绑定所有的

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

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

此外,我们还可以同时绑定多个事件,并为事件处理函数传递一些附加的数据,我们可以通过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 + "!");      
    }           
} );
Copy after login

此外,即使符合条件的元素是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;);
Copy after login

参数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
Copy after login

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

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

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

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


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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!
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).