Home  >  Article  >  Web Front-end  >  Detailed explanation of jQuery.on() function usage

Detailed explanation of jQuery.on() function usage

巴扎黑
巴扎黑Original
2017-07-08 13:51:431834browse

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:

// 为所有P元素分别绑定click事件处理函数handler
$("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.

// 在body元素上绑定click事件处理函数handler,如果这个click事件是由其后代的P元素触发的,就执行handler
$(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代码:

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

我们为dc6dce4a544fdca2df29d5ac0ea9906b中的所有e388a4556c0f65e1904146cc1a846bee元素绑定点击事件:

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

如果要绑定所有的e388a4556c0f65e1904146cc1a846bee元素,你可以编写如下jQuery代码:

//为所有p元素绑定click事件处理程序(注意:这里省略了selector参数)
//n2、n3、n5均可触发该事件
$("p").on("click", function(event){
// 这里的this指向触发点击事件的p元素(Element)
    alert( $(this).text() );
});

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

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(&#39;<p id="n6">上述绑定的click事件对此元素也生效!</p>&#39;);

参数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. 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