是否可以将我的确认条件触发到其他功能?
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>
最佳答案
我建议您通过将要在两个地方使用的逻辑放在两个地方都可以调用的函数中来模块化您的代码:
// 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...*/);
});
})();
关于Javascript:如果确认从不同的函数返回真则触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38924269/