English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The on() method attaches one or more event handlers to the selected element and its child elements.
This also attaches the function to be run when the event occurs.
To remove an event handler, useoff()Method.
To attach an event that runs once and then removes itself, useone()Method.
$.on(event, childSelector, data, function)
Attach the click event to all <p> elements:
$("p").on("click", function() { $.css("background-color", "coral"); });Test and see‹/›
Attach the mouseenter event to all <p> elements:
$("p").on("mouseenter", function() { $.css("background-color", "coral"); });Test and see‹/›
Add multiple event handlers to the <div> element:
$("div").on("mouseenter mouseleave click", function() { $.text(Math.random()); });Test and see‹/›
Pass data to the function:
$("document").ready(function(){ $("p").on("click", {msg: "you just clicked me!!!"}, showMsg) }); function showMsg(event) { $.append(event.data.msg); });Test and see‹/›
UsagechildSelectorThe parameter attaches the click event to all <p> elements:
$("document").ready(function(){ $("body").on("click", "p", changeSize); });Test and see‹/›
Remove the mousemove event from the <div> element:
$("button").click(function(){ $("div").off("mousemove"); });Test and see‹/›
Parameter | Description |
---|---|
event | Specify one or more events or namespaces separated by spaces |
childSelector | (Optional) Specify that the event handler should only be attached to the specified child element (not the selector itself) |
data | (Optional) Specify other data to pass to the function Note:If theDataIf the parameter is provided to the on() method, the parameter will be passed every time the event is triggeredevent.dataPassed to the handler in the attribute |
function | Functionality to be executed when the event is triggered |