我正在尝试设置一个 onbeforeunload 标记,以阻止用户离开特定页面,当且仅当他们有未保存的内容时,并且仅在特定页面上(我们使用单个母版页)。我很快发现在 onbeforeunload 标记中返回 ##anything## 总是会触发 javascript 确认,并将 ##anything## 放在弹出窗口中。显然,这是现在预期的行为,但它确实消除了我使用我自己的可以通过 if 语句控制的确认框的想法。
我试过这个,它没有用:
<body class="yui-skin-sam" onbeforeunload="document.onFormClose();">
<script>
document.onFormClose = function () {
if (document.getElementById('DirtyFlag').value == "true") {
document.getElementById('DirtyFlag').value == "false";
return 'You will lose all changes made since your last save';
}
}
</script>
其中 DirtyFlag 是一个隐藏字段,如果存在任何未保存的更改,则该字段变为真。我希望将 return 放在函数中可以解决问题,但没有这样的运气。
所以我的问题是,有没有办法使用带有内置返回的 onbeforeunload 标签来绕过它等待该字段的值?或者,(尽管这不太理想)我想我可以在我设置或重置 getElementById 标记的所有位置动态添加或删除 onbeforeunload 标记。不幸的是,我也不知道该怎么做。哦,我完全不能使用 jQuery 或任何其他 javascript 库。