最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - "Trigger a click" vs "Function call"? - Stack Overflow

programmeradmin5浏览0评论

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?

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
}

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?

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
}
Share Improve this question asked Jul 17, 2012 at 8:58 Nick ZingerNick Zinger 1,1741 gold badge12 silver badges28 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

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.

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.

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. In do_stuff it will not.

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; 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:

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.

发布评论

评论列表(0)

  1. 暂无评论