Home >Web Front-end >JS Tutorial >jQuery event binding and delegate examples_jquery

jQuery event binding and delegate examples_jquery

WBOY
WBOYOriginal
2016-05-16 16:30:251235browse

The examples in this article describe jQuery event binding and delegation. Share it with everyone for your reference. The specific method is as follows:

JQuery event binding and delegation can be implemented using a variety of methods, on() , bind() , live() , delegate() , and one().

Sometimes we may bind an event like this:

Copy code The code is as follows:
$("#div1").click(function() {
alert("Trigger after click");
});

We can implement the above event binding in a variety of ways:

1. on()

Copy code The code is as follows:
//No data parameters
$("p").on("click", function(){
alert( $(this).text() );
});

//There are data parameters
function myHandler(event) {
alert(event.data.foo);
}
$("p").on("click", {foo: "bar"}, myHandler)

Corresponding to on() is off(), which is used to remove event binding:

Copy code The code is as follows:
var foo = function () {
// code to handle some kind of event
};
// ... now foo will be called when paragraphs are clicked ...
$("body").on("click", "p", foo);

// ... foo will no longer be called.
$("body").off("click", "p", foo);

off(): remove the binding by on()
one(): only bind once.

2. bind()

Parameters:
(type,[data],function(eventObject))
type: A string containing one or more event types, with multiple events separated by spaces. For example, "click" or "submit", or a custom event name.
data: Additional data object passed to the event object as the event.data attribute value

fn: The handler function bound to the event of each matching element

(type,[data],false)
type: A string containing one or more event types, with multiple events separated by spaces. For example, "click" or "submit", or a custom event name.
data: Additional data object passed to the event object as the event.data attribute value

false: Setting the third parameter to false disables the default action.

Bind multiple event types at the same time:

Copy code The code is as follows:
$('#foo').bind('mouseenter mouseleave', function() {
$(this).toggleClass('entered');
});

Bind multiple event types/handlers simultaneously:

Copy code The code is as follows:
$("button").bind({
click:function(){$("p").slideToggle();},
mouseover:function(){$("body").css("background-color","red");},
mouseout:function(){$("body").css("background-color","#FFFFFF");}
});

You can pass some additional data before event handling.

Copy code The code is as follows:
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)


Cancel the default behavior and prevent the event from bubbling by returning false.

Copy code The code is as follows:
$("form").bind("submit", function() { return false; })

Problems with bind

If there are 10 columns and 500 rows in the table to which click events are bound, then finding and traversing 5000 cells will cause the script execution speed to slow down significantly, and saving 5000 td elements and corresponding event handlers will also Takes up a lot of memory (similar to having everyone physically stand at the door waiting for a delivery).

Based on the previous example, if we want to implement a simple photo album application, each page only displays thumbnails of 50 photos (50 cells), and the user clicks "Page x" (or "Next Page") link can dynamically load another 50 photos from the server via Ajax. In this case, it seems that binding events for 50 cells using the .bind() method is acceptable again.

This is not the case. Using the .bind() method will only bind click events to 50 cells on the first page. Cells in subsequent pages that are dynamically loaded will not have this click event. In other words, .bind() can only bind events to elements that already exist when it is called, and cannot bind events to elements that will be added in the future (similar to how new employees cannot receive express delivery).

Event delegation can solve the above two problems. Specific to the code, just use the .live() method newly added in jQuery 1.3 instead of the .bind() method:

Copy code The code is as follows:
$("#info_table td").live("click",function() {/*Show more information*/});

The .live() method here will bind the click event to the $(document) object (but this cannot be reflected from the code. This is also an important reason why the .live() method has been criticized. We will discuss it in detail later. ), and you only need to bind $(document) once (not 50 times, let alone 5000 times), and then you can handle the click event of the subsequent dynamically loaded photo cell. When receiving any event, the $(document) object will check the event type and event target. If it is a click event and the event target is td, then the handler delegated to it will be executed.

unbind(): Removes the binding performed by bind.

3. live()

So far, everything seems perfect. Unfortunately, this is not the case. Because the .live() method is not perfect, it has the following major shortcomings:
The $() function will find all td elements in the current page and create jQuery objects. However, this td element collection is not used when confirming the event target. Instead, a selector expression is used to compare with event.target or its ancestor elements, so Generating this jQuery object will cause unnecessary overhead;
By default, events are bound to the $(document) element. If the DOM nested structure is very deep, events bubbling through a large number of ancestor elements will cause performance losses;
It can only be placed after the directly selected element, and cannot be used after the consecutive DOM traversal method, that is, $("#info_table td").live... can be used, but $("#info_table").find("td" ).live...No;
Collect td elements and create jQuery objects, but the actual operation is the $(document) object, which is puzzling.
The solution
To avoid generating unnecessary jQuery objects, you can use a hack called "early delegation", which is to call .live() outside the $(document).ready() method:

Copy code The code is as follows:
(function($){
$("#info_table td").live("click",function(){/*Show more information*/});
})(jQuery);

Here, (function($){...})(jQuery) is an "anonymous function that is executed immediately", forming a closure to prevent naming conflicts. Inside the anonymous function, the $parameter refers to the jQuery object. This anonymous function does not wait until the DOM is ready before executing. Note that when using this hack, the script must be linked and/or executed in the head element of the page. The reason for choosing this timing is that the document element is available at this time, and the entire DOM is far from being generated; if the script is placed in front of the closing body tag, it makes no sense, because the DOM is fully available at that time.

In order to avoid performance losses caused by event bubbling, jQuery supports the use of a context parameter when using the .live() method starting from 1.4:

Copy code The code is as follows:
$("td",$("#info_table")[0]). live("click",function(){/*Show more information*/});

In this way, the "trustee" changes from the default $(document) to $("#info_table")[0], saving the bubbling trip. However, the context parameter used with .live() must be a separate DOM element, so the context object is specified here using $("#info_table")[0], which is obtained using the array index operator. A DOM element.

4. delegate()

As mentioned earlier, in order to break through the limitations of the single .bind() method and implement event delegation, jQuery 1.3 introduced the .live() method. Later, in order to solve the problem of too long "event propagation chain", jQuery 1.4 supported specifying context objects for the .live() method. In order to solve the problem of unnecessary generation of element collections, jQuery 1.4.2 simply introduced a new method.delegate().

Using .delegate(), the previous example can be written like this:

Copy code The code is as follows:
$("#info_table").delegate("td","click", function(){/*Show more information*/});

Using .delegate() has the following advantages (or solves the following problems of the .live() method):
Directly bind the target element selector ("td"), event ("click") and handler to the "dragee" $("#info_table"), without additional collection of elements, shortened event propagation path, and clear semantics;

Supports calling after the consecutive DOM traversal method, that is, supports $("table").find("#info").delegate..., supporting precise control;

It can be seen that the .delegate() method is a relatively perfect solution. But when the DOM structure is simple, .live() can also be used.

Tip: When using event delegation, if other event handlers registered on the target element use .stopPropagation() to prevent event propagation, the event delegation will become invalid.

undelegate(): Remove the binding of delegate

I hope this article will be helpful to everyone’s jQuery programming.

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