jQuery delegate()Method

jQuery 事件方法jQuery Event Methods

Example

When clicking a <p> element inside a <div> element, change the background color of all <p> elements:

$("div").delegate("p","click",function(){
    $("p").css("background-color","pink");
});

Try it yourself »

Definition and Usage

The delegate() method adds one or more event handlers to the specified elements (child elements of the selected elements) and specifies the function to run when these events occur.

Event handlers using the delegate() method apply to current or future elements (such as new elements created by scripts).

Since jQuery version 1.7,on()the method is the preferred method for adding event handlers to selected elements.


Syntax

$(selector).delegate(childSelector,event,data,function)

Parameter Description
childSelector Required. Specifies one or more child elements to which event handlers are added.
event Required. Specifies one or more events to add to the element.

Multiple event values separated by spaces. Must be valid events.
data Optional. Specifies additional data passed to the function.
function Required. Specifies the function to run when the event occurs.


实例

More Examples

Adding event handlers to future elements
How to use the delegate() method to add event handlers to elements that have not yet been created.

Passing data to the function
How to pass data to a custom-named event handler.


jQuery 事件方法jQuery Event Methods

Other Extensions