Latest web development tutorials

jQuery on () method

jQuery Event Methods jQuery Event Methods

Examples

Adding to the <p> element click event handler:

$("p").on("click",function(){
alert("The paragraph was clicked.");
});

try it"

Definition and Usage

on () method on the selected elements and sub-elements to add one or more event handlers.

JQuery from version 1.7 onwards, on () method is bind (), new alternatives live () and delegate () method. The API method to bring a lot of convenience, we recommend using this method, it simplifies the jQuery code base.

Note: Use on () method to add an event handler for the current and future elements (such as the new element created by the script).

Tip: To remove an event handler, use the off () method.

Tip: To add an event run only once and then removed, please use one () method.


grammar

$(selector).on(event,childSelector,data,function,map)

参数 描述
event 必需。规定要从被选元素移除的一个或多个事件或命名空间。

由空格分隔多个事件值。必须是有效的事件。
childSelector 可选。规定只能添加到指定的子元素上的事件处理程序(且不是选择器本身,比如已废弃的 delegate() 方法)。
data 可选。规定传递到函数的额外数据。
function 可选。规定当事件发生时运行的函数。
map 规定事件映射 ( {event:function, event:function, ...}) ,包含要添加到元素的一个或多个事件,以及当事件发生时运行的函数。


Examples

More examples

From bind () to on ()
How to use the on () to achieve the bind (same effect).

Changing from delegate () to on ( )
How to use the on () to achieve the delegate (the same effect).

From live () to on ()
How to use the on () to achieve and live (the same effect).

Adding multiple event handlers
How to add multiple elements to the event handler.

Use map parameters to add multiple event handlers
How to use the map parameters to add multiple event handlers to the selected element.

On the element to add custom events
How to add a custom namespace event on the element.

Data passed to the function
How to pass data to function.

Add an event handler to the next element
Demo on () method is also applicable to the element has not been created.

Remove event handlers
How to use the off () method to remove an event handler.


jQuery Event Methods jQuery Event Methods