我已经设置了一个带有表单的页面,用户可以使用 PHP 对其进行更改。当他们尝试离开页面或刷新时,会使用 JS 出现一个警告框。但是,当他们单击“保存”按钮时,警报框仍然会出现。
有什么方法可以阻止用户单击“保存”按钮时出现的警告框吗?
这是我的 JS:
var needToConfirm = true;
$('#save').click(function(){
var needToConfirm = false;
})
if (needToConfirm == true)
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Here is my HTML (just the button): -->
<input type="submit" id="save" />
<input type="hidden" id="save" name="submitted" value="TRUE" />
最佳答案
如果我理解正确的话,您不想在有人单击“保存”按钮时显示确认对话框,对吗?为什么不在该点击处理程序中取消注册 onbeforeunload
方法,如下所示:
window.onbeforeunload = confirmExit; //By default assign the confirmExit
//If user clicks on save, just set it to null.
$('#save').click function(){
window.onbeforeunload = null;
}
这样,您就不需要维护名为 needToConfirm
的单独变量。另外,尝试了解 javascript 执行代码的方式。它逐行进行。因此,当用户单击“保存”时,您在点击处理程序中定义的 needToConfirm
现在会被设置为 false
。但即使在调用该回调之前,您也已经绑定(bind)了 onbeforeunload
事件,因为 needToConfirm
的默认值为 true
。
尝试记住 JavaScript 中变量的作用域。如果您在点击处理程序中重新定义变量needToConfirm
,它不一定会访问您打算在不同函数之间共享的“全局”变量。当然,就像其他人指出的那样,不要对不同的 HTML 元素使用相同的 id 。它不应该这样使用。
关于javascript - 如何向用户显示警报框,除非他们单击特定按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40424917/