Javascript:如果确认从不同的函数返回真则触发

标签 javascript php jquery

是否可以将我的确认条件触发到其他功能?

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/

相关文章:

javascript - ngClick 在我的 Angular 应用程序中不起作用

javascript - 为什么我无法检索此 JavaScript\JQuery 函数中 select 标签的内容?

javascript - 变量没有在 php 中相乘

php - 如何在 PHP 上使用 DOM 将 PHP 代码添加到属性?

javascript - jQuery Rain "Animated Menu Icon"onclick 不工作

javascript - 拆分附加表(JQuery 或 JavaScript)

php - 将 php 数组传递给 jqplot 图表

javascript - JQuery获取同名属性值

javascript - 快速鼠标悬停鼠标移出时的动画错误

php - 我的更新 cade 有什么问题吗?