gpt4 book ai didi

javascript - 我如何要求用户确认他们要离开页面?

转载 作者:行者123 更新时间:2023-11-30 20:48:24 24 4
gpt4 key购买 nike

我有一个包含多个页面的网站,用户可以在其中添加和编辑信息。为了提供一致的 UI,我有以下 JavaScript 函数...

function setWindowBeforeUnload(changed) {
$(window).on("beforeunload", function() {
if (confirmLeave && changed && changed()) {
return "You haven't saved the information. If you leave this page, the information will be lost.";
}
});
}

confirmLeave 是一个全局变量,指定我们是否要在导航离开之前要求他们确认(如果我们在成功保存后导航到另一个页面,我们不会这样做)。 changed 是检查实体是否已更改的函数。

这是从详细信息页面(比如客户页面)调用的,如下所示...

$(document).ready(function() {
setWindowBeforeUnload(customerChanged);
});

function customerChanged() {
// Checks the data and returns true or false as appropriate
}

这一切都很好,直到最近,当一个 change in Chrome打破它。

我搜索了几个小时,发现很多人都建议这样的代码...

addEventListener('beforeunload', function(event) {
event.returnValue = 'You have unsaved changes.';
});

...它可以正常工作,只是每当他们离开页面时都会发出警告,无论数据是否已更改。

一旦我尝试添加任何逻辑(例如我在第一个示例中的检查代码),它就不起作用...

function setWindowBeforeUnload(changed) {
addEventListener('beforeunload', function(event) {
if (confirmLeave && changed && changed()) {
event.returnValue = 'You have unsaved changes.';
}
});
}

使用此代码,我可以在不收到警告的情况下离开该页面。

现在有什么方法可以重现我原来的行为吗?

最佳答案

您可以在处理程序中使用逻辑,只是不能再有自定义消息了。请参阅下面的代码。使用“运行代码片段”来模拟导航。运行代码段,再次运行它没有确认。将按钮切换为“false”运行代码段并获得确认。

var test = true;

function otherTest() {
return true;
}

addEventListener('beforeunload', function(event) {
if(!test || !otherTest()) {
event.returnValue = 'You have unsaved changes.';
}

});

document.getElementById('theButton').addEventListener('click', function(event) {
test = !test;
this.innerHTML = test.toString();
});
<p>Click the button to turn the confirm on and off</p>
<button id="theButton">true</button>

关于javascript - 我如何要求用户确认他们要离开页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48449647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com