简体   繁体   English

jQuery-“触发点击”与“函数调用”?

[英]jQuery - “Trigger a click” vs “Function call”?

Say I have some actions binded to a link ( with .click or .live), and I want to do the same thing later, but I don't want duplicated code. 假设我有一些绑定到链接的动作(使用.click或.live),我想稍后再做同样的事情,但是我不想重复的代码。 Which is the correct way and why? 哪种方法正确,为什么?

This: 这个:

$('#link').click(function(){
 //do stuff
});

//called later
$('#link').trigger('click');

OR: 要么:

$('#link').click(function(){
  do_stuff();
});

//called later
do_stuff();

//defined here
function do_stuff(){
   //do stuff
}

Actually, you only need to distinguish between whether or not you're accessing the event object within the event handler. 实际上,您只需要区分是否在事件处理程序中访问event object Another difference is that the context of that invoked handler might change, so this won't point to the invoked node when called directly. 另一个区别是该被调用处理程序的上下文可能会更改,因此当直接调用该node时, this不会指向被调用node

If you're accessing this or the event object , you indeed should use .trigger to execute the handler. 如果要访问this event objectevent object ,则确实应该使用.trigger执行处理程序。 You could also pass in all necesarry data yourself by manually invoking the method, but why invent the wheel. 您也可以通过手动调用该方法来自己传递所有necesarry数据,但是为什么要发明轮子呢?

Otherwise, you're just fine in directly calling that function from wherever you have access to it. 否则,您可以在任何有访问权限的地方直接调用该函数。

Note that context will differ in your code depending on the two actions. 请注意,根据这两个操作,上下文在您的代码中将有所不同。

In your anonymous callback function, this will refer to the link being clicked. 在您的匿名回调函数中, this将指向被单击的链接。 In do_stuff it will not. do_stuff不会。

Other than that, I think it is often more semantically appealing to call a function that does what you want to do, than to simulate a click that has the side effect of triggering your listener. 除此之外,我认为调用一个可以执行您想要的功能的函数在语义上通常比模拟具有触发您的侦听器的副作用的单击更具吸引力。 This is my personal preference, though. 不过,这是我的个人喜好。

One problem with your first method is that you'll also trigger any other click events that get bound to that control; 第一种方法的一个问题是,您还将触发绑定到该控件的任何其他click事件。 you can solve this with namespaces 您可以使用名称空间解决此问题

$('#link').bind('click.mynamespace', function(){ ... });

$('#link').trigger('click.mynamespace');

or by using a second event 或通过使用第二个事件

$('#link').bind('do_stuff', function(){ ... });
$('#link').click(function() { $(this).trigger('do_stuff'); });

However I'd go for the second one because it's simpler, provided you have closure access to the function where you need to call it. 但是,我将继续第二个,因为它比较简单,只要您可以在需要调用该函数的地方进行关闭访问即可。 You don't need the extra function wrapper, BTW: 您不需要额外的功能包装器BTW:

function do_stuff(event) { ... }
$('#link').click(do_stuff);
do_stuff();

If it is useful to define the function in a closure you no longer have access to, go for the first way. 如果在不再有权限访问的闭包中定义函数很有用,请采用第一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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