How to use the jQuery.delegate() function?
The jQuery.delegate() function is used to dynamically bind event handlers to current or future elements.
The usage instructions are as follows:
- Basic grammar.
$(selector).delegate(childSelector, eventType, function)
- Selector: Represents the parent element to which the event will be bound.
- childSelector: A selector that specifies the child element where the event will be bound.
- eventType: a string that represents the type of event to be bound, such as “click” or “mouseover”.
- function: callback function, which represents an event handler.
- Sample code:
$(document).delegate("button", "click", function(){
// 在点击button元素时触发的事件处理程序
$(this).text("Clicked");
});
The above code binds a click event handler to all button elements in the document, so that when a button is clicked, the event handler is triggered and changes its text to “Clicked”.
- Important points to note:
- It is recommended to use the .on() function instead of the .delegate() function in versions of jQuery after 3.0.
- It is not recommended to use the .delegate() function if the .on() function has already been used.
- If the selector matches multiple elements, each in different parents, the event handler will trigger on all matching children.
For more information on the jQuery.delegate() function, please refer to the official documentation: jQuery.delegate()