jQuery trigger()Method

jQuery 事件方法jQuery Event Methods

Example

Trigger the select event of the <input> element:

$("button").click(function(){ $("input").trigger("select"); });

Try it Yourself »

Definition and Usage

The trigger() method triggers the specified event on the selected elements, as well as the default behavior of the event (such as form submission).

This method is similar to thetriggerHandler()method, the difference being that triggerHandler() does not trigger the default behavior of the event.

Differences compared with the triggerHandler() method:

  • The trigger() method does not cause the default behavior of events (such as form submission).
  • trigger() operates on all elements matched by the jQuery object, while triggerHandler() only affects the first matched element.
  • Events created by triggerHandler() will not bubble up the DOM tree; if the target elements do not handle them directly, nothing will happen.

Example

Comparing triggerHandler() with .trigger():

$( "#old" ).click(function() { $( "input" ).trigger( "focus" ); }); $( "#new" ).click(function() { $( "input" ).triggerHandler( "focus" ); }); $( "input" ).focus(function() { $( "<span>Focused!</span>" ).appendTo( "body" ).fadeOut( 1000 ); });

Try it Yourself »

If you want to trigger the default behavior of a link, such as linking to a specified URL, you need to call theevent.preventDefault()method in the event handler function, for example:

Example

$('#myLink').on('click', function(event) { event.preventDefault(); window.location.href = 'https://www.example.com'; });

Try it Yourself »

Syntax

$(selector).trigger(event,eventObj,param1,param2,...)

Parameter Description
event Required. Specifies the event to trigger on the specified elements.
Can be a custom event, or any standard event.
param1,param2,... Optional. Additional parameters to pass to the event handler.
Additional parameters are especially useful for custom events.


实例

More Examples

Passing additional parameters to custom events
How to pass additional parameters to a custom event handler.

The difference between trigger() and triggerHandler()
Demonstrates the difference between trigger() and triggerHandler().


jQuery 事件方法jQuery Event Methods

Other Extensions