jQuery delegate() method
Example
When clicking the
element, change all
elements' background color:
$("div").delegate("p","click",function(){
$("p").css("background-color","pink");
});
Try it »
Definition and Usage
The delegate() method adds one or more event handlers to the specified elements (children of the selected elements), and specifies a function to run when these events occur.
Event handlers added with the delegate() method apply to current and future elements (such as new elements created by a script).
Since jQuery version 1.7,on() method is the preferred way to add event handlers to selected elements.
Syntax
$(
selector
).delegate(
childSelector,event,data,function
)
| Parameters | Description |
|---|---|
| childSelector | Required. Specifies one or more child elements to which event handlers are to be added. |
| event | Required. Specifies one or more events to add to the element. |
由空格分隔多个事件值。必须是有效的事件。 |
| data | Optional. Specifies additional data passed to the function. | | function | Required. Specifies the function to run when the event occurs. |
More examples
Add event handlers to future elements
How to use the delegate() method to add event handlers to elements that have not yet been created.
Pass data to the function
How to pass data to a custom-named event handler.
jQuery event methods