jQuery - 调用.trigger('click')vs .click() [英] jQuery - Calling .trigger('click') vs .click()

查看:169
本文介绍了jQuery - 调用.trigger('click')vs .click()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中触发click等事件的更好方法是什么?使用 .trigger('click')函数或调用 .click()

In jQuery what is the better way to trigger an event such as click? Using the .trigger('click') function or calling .click()?

我总是使用 .click()触发此事件,但突然决定我应该使用 .trigger( 点击)代替。

I have always triggered this event by using .click() but suddenly decided maybe I should be using .trigger('click') instead.

我使用这些事件触发器来触发用 .on('click',function(){...})创建的事件监听器

I use these event triggers to trigger event listeners created with .on('click', function(){...}).

我查看了 jquery api ,搜索了其他stackoverflow帖子 [1] [2] 我认为没有理由使用其中一个。

I have checked the jquery api, searched other stackoverflow posts [ 1 ] [ 2 ] and I can see no reason to use one over the other.

我更倾向于使用 .trigger()来保持所有事件触发一致,因为这可以用于调用任何事件,包括自定义事件但似乎 .trigger()在所有情况下都不起作用。

I would be more inclined to use .trigger() to keep all event triggering consistent, as this can be used to call any event including custom events. But it would seem .trigger() does not work in all cases.

触发的最佳方式是什么一个事件? .trigger('click') .click()

What is the best way to trigger an event? .trigger('click') or .click()?

推荐答案

如果您使用的是 .trigger(),则可以传递其他参数,而 .click()必须不带任何调用。

If you're using .trigger() you have the advantage of being able to pass additional parameters, whereas .click() must be called without any.

取自文档

$('#foo').bind('custom', function(event, param1, param2) {
  alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

'自定义''Event'正作为 param1 param2 分别

'Custom' and 'Event' are being passed to the event handler as param1 and param2 respectively

除此之外, .click()与其他实现get的函数不同/基于参数的数量设置,因为它实现了触发/设置。对我来说,使用专用的 .trigger()更合乎逻辑。

Besides that, the .click() is unlike other functions that implement get / set based on the number of arguments, because it implements trigger / set instead. Using a dedicated .trigger(), to me, is more logical.

这篇关于jQuery - 调用.trigger('click')vs .click()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆