我會建議你通過把要在兩個地方在函數中使用兩個地方可以調用邏輯模塊化代碼:
// 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