2016-08-12 38 views
1

是否可以觸發我的確認條件爲其他功能?Javascript:觸發如果確認返回從不同功能返回true

myphp.php

<input type="button" id="button1" class"button2"> 

<script> 
$('#button1').on('click', function(){ 
if(confirm("Are you sure?")){ 
    //my stuff 
}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) 
}); 
</script> 
+1

'如果(真){$(」按鈕2)。點擊()}' –

+2

@u_mulder:這會帶來不可維護的麪條。 :-) –

+2

只有另一個命名函數可以從兩個事件處理函數中調用嗎? – adeneo

回答

5

我會建議你通過把要在兩個地方在函數中使用兩個地方可以調用邏輯模塊化代碼:

// 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...*/); 
    }); 
})();