【问题标题】:SweetAlert while navigating to other page导航到其他页面时的 SweetAlert
【发布时间】:2017-09-01 06:37:08
【问题描述】:

在我的应用程序中,如果我没有点击保存并想从当前页面导航,它应该询问甜蜜警报are you sure want to leave? 和两个按钮save and leave。我该怎么做。

目前我正在使用 jquery,当我单击任何锚标记但立即导航到其他页面时,它会显示 sweetalert 框。

我的代码是

jQuery(document).click(function(e) {
                if (jQuery(e.target).is('a')) {
                    swal({
                        title: "Are you sure?",
                        text: "Want to continue without saving?",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "Leave",
                        closeOnConfirm: false,
                        html: false
                        }

                    );
                }    
        }); 

【问题讨论】:

  • 看看preventDefault() ...

标签: javascript jquery angularjs


【解决方案1】:

首先,您需要防止<a> 元素的默认行为,因为您错过了它,它仍然会重定向您的操作,其次是如果在swal 中单击确认,您需要重定向用户,例如:

jQuery(document).click(function(e)
{
  if (jQuery(e.target).is('a'))
  {
    // Prevent default behavior
    e.preventDefault();

    swal({
      title: "Are you sure?",
      text: "Want to continue without saving?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Leave",
      closeOnConfirm: false,
      html: false
    }, function (isConfirm) {

      if (isConfirm)
      {
        // If user clicked confirm navigate away
        window.location = jQuery(e.target).attr("href");
      }
    });

    return false;
  }
});

希望对你有帮助

【讨论】:

  • 我试过这个..但是当页面第一次加载时它会触发甜蜜警报
  • 我实际上在小提琴中检查了它,您的问题并没有持续存在,您的代码中是否有类似的声明?
  • 没有。。这是唯一的地方。但我没有把它放在任何功能中。需要吗?
  • 如果仍然存在,请尝试用jQuery.ready(function () { //stuff } ); 包裹它
  • 它工作正常,。唯一的问题是当该页面加载时它也会触发sweetalert。我不想要那个。页面加载后,它工作正常。
【解决方案2】:

看看 Event.preventDefault() 或 e.preventDefault()

该锚标记a 将创建一个事件以导航到其网址,即使它是href=#

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多