jQuery - 调用.trigger('click')vs .click() [英] jQuery - Calling .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 $ c $传递给事件处理程序c>分别
'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屋!