2016-08-12 37 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...*/); 
    }); 
})();