是否可以将我的确认条件触发到其他功能?
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>
答案 0 :(得分: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...*/);
});
旁注:我已经在你的剧本的顶层展示了它,但如果你还没有(并且你没有提到你的问题),我会建议所有您的代码在立即调用的作用域函数中,以避免全局变量:
(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...*/);
});
})();