jQuery - “触发点击” vs“功能调用”? [英] jQuery - "Trigger a click" vs "Function call"?

查看:94
本文介绍了jQuery - “触发点击” vs“功能调用”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一些绑定到链接的动作(使用.click或.live),我想稍后做同样的事情,但我不想要重复的代码。这是正确的方法和原因?

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. Which is the correct way and why?

这个:

$('#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
}


推荐答案

实际上,您只需要区分您是否正在访问事件对象在事件处理程序中。另一个区别是该调用的处理程序的 context 可能会更改,因此将不会指向调用的节点直接调用。

Actually, you only need to distinguish between whether or not you're accessing the event object within the event handler. Another difference is that the context of that invoked handler might change, so this won't point to the invoked node when called directly.

如果您正在访问事件对象,你确实应该使用 .trigger 来执行处理程序。您也可以通过手动调用方法自己传递所有necesarry数据,但为什么要发明轮子。

If you're accessing this or the event object, you indeed should use .trigger to execute the handler. You could also pass in all necesarry data yourself by manually invoking the method, but why invent the wheel.

否则,您可以从任何地方直接调用该函数你可以访问它。

Otherwise, you're just fine in directly calling that function from wherever you have access to it.

这篇关于jQuery - “触发点击” vs“功能调用”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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