简体   繁体   中英

jQuery programmatically trigger events

What all events can be triggered programmatically using jQuery? Also is there any important differences to be remembered when one is doing event triggering using jQuery Vs a natural way of it being triggered?

Every event can be programmatically fired, just use the callback-less version of it.

Example:

$('#button').click(function() { alert('event hanlder'); });

$('#button').click(); // generate the event

About your second question, there should be no difference between the native and jQuery event handlers.


One thing that is neat though is that jQuery binds this to the element that received the event, inside the callback (this doesn't happen in native event handlers):

$('#button').click(function() { alert(this); }); // here 'this' == document.getElementById('button');

Warning: the element referenced by this is not "jQuery augmented". If you want to traverse or modify it with jQuery goodness you'll have to do something like var $this = $(this);

You should know the differences between trigger and triggerHandler in jQuery.

trigger

trigger attempts to replicate the natural event as best as it can. The event handler for the event being triggered get's executed, but the default browser actions will not always be replicated exactly. For example $('a#link).trigger('click'); will execute the javascript function bound to the links click event handler, but will not redirect the browser to the href of the anchor, like a normal click would. EX: http://jsfiddle.net/AxFkD/

All the short forms of the trigger call behave exactly like trigger IE. click() , mouseup() , keydown() , etc

triggerHandler

triggerHandler prevents bubbling up ( EX. http://jsfiddle.net/LmqsS/ ), it avoids default browser behaviour and just executes the events callback, and it returns the return value of the event handler instead of a jQUery object for chaining.

You should also be aware that trigger affects all elements matched by a selector, but triggerHandler only affects the first one EX: http://jsfiddle.net/jvnyS/

You can trigger any event programmatically. But most of the events cannot be simulated as the natural event using programmatic triggers.

//to trigger a click event on a button

$("buttonSelector").trigger("click");

First, for obvious reasons, you cannot trigger the ready event.

That said, events raised by trigger() behave the same way as if they were triggered by the user. In particular, the event handlers are called in the same order.

The only difference I know of is that triggered events did not bubble up the DOM tree in older versions of jQuery (that behavior was fixed in version 1.3).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM