Attach a click event to the <p> element:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>//from ww w . j av a2s .c o m <script> $(document).ready(function(){ $("p").on("click", function(){ document.getElementById("demo").innerHTML = "The paragraph was clicked."; }); }); </script> </head> <body> <p id="demo"></p> <p>Click this paragraph.</p> </body> </html>
The on()
method attaches one or more event handlers for the selected elements and child elements.
As of jQuery version 1.7, the on()
method replaces the bind()
, live()
and delegate()
methods.
Event handlers attached using the on()
method will work for both current and future elements.
To remove event handlers, use the off()
method.
To attach an event that only runs once and then removes itself, use the one()
method.
$(selector).on(event,child_Selector,data,function,map)
Parameter | Optional | Description |
---|---|---|
event | Required. | one or more event(s) or namespaces to attach to the selected elements. Multiple event values are separated by space. |
child_Selector | Optional. | the event handler should only be attached to the specified child elements |
data | Optional. | additional data to pass to the function |
function | Required. | function to run when the event occurs |
map | Optional. | an event map ({event:function, event:function, ...}) |