jQuery on() method
Example
towards
element, add a click event handler:
$
(
document
)
.
ready
(
function
(
)
{
$
(
"
p
"
)
.
on
(
"
click
"
,
function
(
)
{
alert
(
"
The paragraph was clicked.
"
)
;
}
)
;
}
)
;
Try it »
Definition and Usage
The on() method adds one or more event handlers to the selected elements and their children.
Since jQuery version 1.7, the on() method is the new replacement for the bind(), live(), and delegate() methods. This method brings many conveniences to the API; we recommend using it, as it simplifies the jQuery codebase.
**Note:** Event handlers added with the on() method apply to current and future elements (such as new elements created by a script).
**Tip:** To remove event handlers, use the off() method.
**Tip:** To add an event that runs only once and is then removed, use the one() method.
Syntax
$(
selector
).on(
event,childSelector,data,function
)
| Parameters | Description |
|---|---|
| event | Required. Specifies one or more events or namespaces to add to the selected elements. |
由空格分隔多个事件值,也可以是数组。必须是有效的事件。 |
| childSelector | Optional. Specifies event handlers that can only be added to specified child elements (and not the selector itself, like the deprecated delegate() method). | | data | Optional. Specifies additional data passed to the function. | | function | Optional. Specifies the function to run when the event occurs. |
More examples
Switching from bind() to on()
How to use on() to achieve the same effect as bind().
Switching from delegate() to on()
How to use on() to achieve the same effect as delegate().
Switching from live() to on()
How to use on() to achieve the same effect as live().
Add multiple event handlers
How to add multiple event handlers to an element.
Add multiple event handlers using the map parameter
How to use the map parameter to add multiple event handlers to selected elements.
Add a custom event on an element
How to add a custom namespaced event on an element.
Pass data to the function
How to pass data to a function.
Add event handlers to future elements
Demonstrate that the on() method also applies to elements that have not yet been created.
Remove event handlers
How to use the off() method to remove event handlers.
jQuery event methods