开发者

Trigger multi-events

Can I trigger multi events in trigger() or chain them in JQuery!? E.g:

$开发者_StackOverflow(element).trigger('event1 event2 event3');

or

$(element).trigger('event1').trigger('event2');

or

$(element).trigger('event1');
$(element).trigger('event2');


As other answers note, the best built-in method is:

$(element).trigger('event1').trigger('event2');

However, I find that if you're doing this all over the place, a simple plugin cleans it up quite nicely, allowing the space-separated syntax (like other jQuery methods). Here's a quick example of such a plugin:

$.fn.triggerAll = function(events) {
    if(!events) return this; //don't blow up if .triggerAll() without params
    var self = this;         //keep a reference
    $.each(events.split(" "), function(i, e) { self.trigger(e); });
    return this;
};

Then you can call it with space-separated event names, like this:

$(element).triggerAll('event1 event2 event3');

You can test it out here


$(element).trigger('event1 event2 event3');

is not supported.

(element).trigger('event1').trigger('event2');

is optimal over

$(element).trigger('event1');
$(element).trigger('event2');

as you are not rebuilding the jQuery object containing $(element) each time you trigger an event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜