1、一般方法(存在刷新问题)
a.htm (父窗口)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>父窗口</title>
<script language="javascript">
var wind; //全局变量
function winopen()
{
wind=window.open("b.htm","childwind","",""); //打开子窗口
}
function winclose()
{
if(typeof(wind)!="undefined"&&wind.open&&!wind.closed) //判断是否存在子窗口并处于打开状态
{
wind.close(); //关闭子窗口
}
}
</script>
</head>
<body>
<input type="button" value="打开子窗口" id="btn1" onclick="winopen();">
<input type="button" value="关闭子窗口" id="btn2" onclick="winclose();">
</body>
</html>
存在问题:当父窗口进行刷新时,wind将等于undefined,所以无法找到子窗口并将其关闭
2、我的方法(解决刷新问题)
a.htm (父窗口)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>父窗口</title>
<script language="javascript">
var wind; //全局变量
function winopen()
{
wind=window.open("b.htm","childwind","",""); //打开子窗口,注意链接地址为:b.htm你要打开的页面
}
function winclose()
{
wind=window.open("b.htm","childwind","",""); //打开子窗口,注意窗口名与上面的一样:childwind,链接地址为:c.htm用于处理关闭
}
</script>
</head>
<body>
<input type="button" value="打开子窗口" id="btn1" onclick="winopen();">
<input type="button" value="关闭子窗口" id="btn2" onclick="winclose();">
</body>
</html>
c.htm (处理关闭的页面)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>新建网页 1</title>
<script language="javascript">
function winopen()
{
window.close(); //将自身关闭
}
</script>
</head>
<body onload="winopen();">
</body>
</html>
本文介绍了一种在父窗口刷新后仍能正确关闭子窗口的方法。通过使用特定的 JavaScript 技巧,确保即使在父窗口刷新的情况下,也能找到并关闭之前打开的子窗口。这种方法对于需要频繁打开和关闭窗口的应用场景非常有用。
&spm=1001.2101.3001.5002&articleId=1585659&d=1&t=3&u=e3a4717f38fa42658be79a41f787a15b)
1156

被折叠的 条评论
为什么被折叠?



