我会建议你通过把要在两个地方在函数中使用两个地方可以调用逻辑模块化代码:
// The function doing the thing
function doTheThing(/*...receive arguments here if needed...*/) {
// ...
}
$('#button1').on('click', function(){
if(confirm("Are you sure?")){
doTheThing(/*...pass arguments here if needed...*/);
}else{
return false;
}
});
$('.button2').on('click', function(){
//if the confirm condition from first function return true
//i need to fire here as well without doing another if(confirm)
doTheThing(/*...pass arguments here if needed...*/);
});
注意:我已经在脚本的顶层显示了它,但是如果你还没有(并且你没有在你的问题中),我会建议把你的c的全部颂在立即调用的作用域功能,以避免全局变量:
(function() {
// The function doing the thing
function doTheThing(/*...receive arguments here if needed...*/) {
// ...
}
$('#button1').on('click', function(){
if(confirm("Are you sure?")){
doTheThing(/*...pass arguments here if needed...*/);
}else{
return false;
}
});
$('.button2').on('click', function(){
//if the confirm condition from first function return true
//i need to fire here as well without doing another if(confirm)
doTheThing(/*...pass arguments here if needed...*/);
});
})();
'如果(真){$(”按钮2)。点击()}' –
@u_mulder:这会带来不可维护的面条。 :-) –
只有另一个命名函数可以从两个事件处理函数中调用吗? – adeneo