jQuery In 1.7.delegate() has been replaced by .on(). The following is an example of the usage and difference between delegate and on in jQuery. Interested friends can refer to the following
In jQuery1.7.delegate() has been replaced by .on(). As with earlier versions, it is still the most efficient means of using event delegation.
In event binding and delegation, delegate() and on are generally equivalent.
.delegate() adds one or more event handlers to the specified element (a child element belonging to the selected element) and specifies the functions to be run when these events occur.
The code is as follows:
// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, [selector], data, handler );
For example: .delegate() code:
The code is as follows:
$("table").delegate("td","click",function(){
alert("hello");
});
.on () code:
The code is as follows:
$("table").on("click", "td", function() {
alert("hi ");
});
PS: The difference between the two is that the order of selector and events is different.
The child elements of the element selected by the delegate and on methods must be "legal" child elements. For example
The code is as follows:
$("table").delegate("button","click",function(){...});
$ ("table").on("click", "p", function(){...});
will not work, because under normal circumstances, table sub-elements should be tr, td ...
on(events,[selector],[data],fn), the parameter [selector] is optional,
a selectorString is used for filter Descendants of the selector element that triggered the event.
For example:
The code is as follows:
$("table").on("click", ".td1", function() {
alert( "hi");
});
Filter table sub-elements with class td1
and the delegate selector is required.
The above is the detailed content of The usage differences between delegate and on in jQuery and their examples. For more information, please follow other related articles on the PHP Chinese website!