【问题标题】:Sweet alert not returning true or false?甜蜜警报不返回真假?
【发布时间】:2021-06-30 11:58:16
【问题描述】:

Sweet-alert 在调用此 get_alert() 函数后未返回 true 或 false,请提出一些建议,我们如何才能做到这一点

function get_alert() {
  $('#removeactive').on('click', function(e) {
    e.preventDefault();
    var message = $(this).data('confirm');

    //pop up
    swal({
        title: "Are you sure ??",
        text: message,
        icon: "warning",
        buttons: true,
        dangerMode: true,
      })
      .then(function(isConfirm) {
        console.log(isConfirm == true);
        if (isConfirm == true) {
          return true;
        } else {
          return false;
        }
      });
  });
}
<button id="removeactive" data-confirm="Are you sure?" type="button">Click</button>

【问题讨论】:

标签: javascript laravel sweetalert


【解决方案1】:

您应该不需要函数来分配事件处理程序。此外,当您致电 get_alert 时,您也没有告诉我们。调用 get_alert 不会显示警报,只分配处理程序

这里我在加载页面时运行

如果removeactive元素是动态的,则需要改为

$(document).on('click','#removeactive', function(e) {

或更好:

$(document).on('click','.removeactive', function(e) {

因此任何具有该类的元素都可以调用警报

您还需要在您知道 isConfirm 状态的情况下删除 active

这是一个工作示例

$(function() { // on page load
  $('#removeactive').on('click', function(e) {
    e.preventDefault();
    var message = $(this).data('confirm');

    //pop up
    swal({
        title: "Are you sure ??",
        text: message,
        icon: "warning",
        buttons: true,
        dangerMode: true,
      })
      .then(function(isConfirm) {
        console.log("confirmed?", isConfirm);
        if (isConfirm) console.log("deleting"); // here you delete
        else console.log("cancelled"); // here you do whatever or nothing
        // You cannot return anything  
      });
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>

<button id="removeactive" data-confirm="This will remove the active widget from the sprocket" type="button">Click</button>

【讨论】:

  • 我将相同的函数调用到另一个函数中,它没有返回任何内容
  • 您没有发布足够的信息 - 在加载页面时,您无法“调用函数”来运行任务。如果您的removeactive 是动态加载的,您只能拥有其中一个并且您需要委托(ID 必须是唯一的)
  • get_alert() 我正在调用另一个函数
  • 您应该不需要函数来分配事件处理程序。此外,当您致电 get_alert 时,您也没有告诉我们。调用 get_alert 不会显示警报,只分配处理程序
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
相关资源
最近更新 更多