我想知道当用户尝试关闭“Ask Question”页面时,如何在用户试图跳出页面时显示确认框,例如StackOverflow中的此处。JavaScript中的Yes/No框像这样在StackOverflow中这样吗?
非常感谢您。
我想知道当用户尝试关闭“Ask Question”页面时,如何在用户试图跳出页面时显示确认框,例如StackOverflow中的此处。JavaScript中的Yes/No框像这样在StackOverflow中这样吗?
非常感谢您。
事实上,所有需要的是这样的:
window.onbeforeunload = function(){ return "You should save your stuff."; }
这也是这种类型的重复数据删除:How to show the "Are you sure you want to navigate away from this page?" when changes committed?
这是基于浏览器。
只要您实施<form>
标记,并且您在表单中键入了某些内容,并且在Google Chrome中,它会提示您该消息。
您想要赶上window
的onbeforeunload
事件。然后,如果您返回一个字符串,浏览器将在提示中显示您的消息。这里是an article with sample code。
在JavaScript中,附加功能window.onbeforeunload
,像这样:
window.unbeforeunload = function (e)
{
// return (prompt ('Are you sure you want to exit?'));
// EDIT: Amended version below:
var e = e || window.event;
if (e) e.returnValue = 'Your exit prompt';
return 'Your exit prompt';
}
编辑: 正如下面的评论指出,我误解了事件的工作。它现在应该按照预期工作。
-1在我的测试中不起作用。没有提示。 – 2010-01-19 05:47:28
这不起作用。您需要移除“提示”并返回字符串:'return'您将失去任何未保存的更改';'它将围绕您返回的文本包含类似“您确定要离开此页面吗?然后选择文字,然后按“确定”继续,或按“取消”继续保留当前页面。“ – Nicole 2010-01-19 05:50:21
Renesis是正确的 - 这是这个剧本的真正问题。这是对这个功能目的的误解。 – 2010-01-19 05:51:51
可以使用window.onbeforeunload事件赶上这一点。如果textarea内有任何值,则会显示警告消息。
可能是欺骗:How do you prevent a webpage from navigating away in JavaScript?,但你可以通过添加一个代表到window.onbeforeunload事件
<script type="text/javascript">
window.onbeforeunload = function() {
//will show a dialog asking the user if
//they want to navigate away from the current page
// ok will cause the navigation to continue,
// cancel will cause the user to remain on the current page
return "Use this text to direct the user to take action.";
}
</script>
更新这样做:卫生署!更新后的代码做什么OP真正想要的:d
-1如果您在评论中指明的地方返回false,实际上会显示一个对话框,显示“false”; – 2010-01-19 05:50:37
现在很好。 :-) Un-1。 – 2010-01-19 05:58:14
大声笑是的,如果我早一点发现,会很好,谢谢! – Jared 2010-01-19 05:59:15
我怀疑你误会了问题...我会删除这个答案,然后它会花费你一堆点:) – 2010-01-19 05:34:59