使用JavaScript在离开页面前通过onbeforeunload判断并提示用户

作者:闭包旅人时间:2026-10-28 09:55:37浏览:653

本文介绍如何在HTML页面中使用JavaScript的onbeforeunload事件,在用户尝试关闭或离开当前页面前进行条件判断。通过获取特定输入框的值,若为空则弹出确认对话框,防止用户误操作离开页面。

</html>

具体实现代码如下所示:

 
JavaScript离开页面提示实现代码<!doctype html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>js离开当前页面前判断条件提示是否要离开页面</title>
<script type="text/javascript">
window.onbeforeunload = function() {
{ 
var unloads = document.getElementById("unloads").value;
if(unloads == null || unloads == "") {
return "您确定要退出页面吗?";
} 
} 
}
</script>
</head>
<body>
<input type="text" id="unloads" name="unloads" value="" />
</body>
作者最新文章