【问题标题】:Making the leaving site confirm dialog not showing up when a button on the page is clicked单击页面上的按钮时,使离开站点确认对话框不显示
【发布时间】:2019-07-21 02:32:21
【问题描述】:

我最近在我的页面中添加了一个 JavaScript 对话框,它可以让用户确认他们是否真的想离开该页面。但是,我的页面上也有导航到其他页面的按钮,并且我不希望在用户单击这些按钮时显示离开站点确认对话框。

我还没有真正找到如何做到这一点的方法,部分原因是我是 HTML 和 JavaScript 的新手。

下面是我用于确认对话框的代码,我也是从 Stack Overflow 上的 here 获得的。

window.onbeforeunload = function (e) {
    e = e || window.event;

    if (e) {     // For IE and Firefox prior to version 4
        e.returnValue = 'Any string';
    }

    return 'Any string';     // For Safari
};

【问题讨论】:

标签: javascript


【解决方案1】:

您可以使用全局变量来控制导航方式。

这里是一个例子,我使用一个名为needConfirm的变量来处理网页是否显示确认消息。

var needConfirm = true;
window.onbeforeunload = function (e) {
  if (!needConfirm) {
    return; // do nothing, just redirect...
  }

  e = e || window.event;

  if (e) {     // For IE and Firefox prior to version 4
    e.returnValue = 'Any string';
  }

  return 'Any string';     // For Safari
};

// function to change needConfirm value to `false`
function disableConfirm() {
  needConfirm = false;
}

调用 disableConfirm() onClick 获取您想要允许的按钮和链接。例如

<a href="/other_page_url" onClick="disableConfirm()">Redirect without confirmation...</a>

【讨论】:

    猜你喜欢
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多