在JavaScript中,关闭子窗口并刷新父窗口通常涉及到window.close()
方法和window.opener
对象的使用。以下是具体的实现步骤和示例代码:
window.close()
: 这个方法用于关闭当前窗口。window.opener
: 这个属性指向打开当前窗口的那个窗口对象。window.close()
方法关闭子窗口。window.opener.location.reload()
方法刷新父窗口。假设父窗口的HTML文件为parent.html
,子窗口的HTML文件为child.html
。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Parent Window</title>
<script>
function openChildWindow() {
window.childWindow = window.open('child.html', 'ChildWindow', 'width=400,height=300');
}
</script>
</head>
<body>
<button onclick="openChildWindow()">Open Child Window</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Child Window</title>
<script>
function closeAndRefreshParent() {
if (window.opener && !window.opener.closed) {
window.opener.location.reload();
}
window.close();
}
</script>
</head>
<body>
<button onclick="closeAndRefreshParent()">Close and Refresh Parent</button>
</body>
</html>
openChildWindow()
函数会被调用,打开一个新的子窗口。window.open()
方法的第二个参数是窗口名称,第三个参数是窗口特性(如宽度和高度)。closeAndRefreshParent()
函数会被调用。window.opener.location.reload()
方法会刷新父窗口。window.close()
方法会关闭当前子窗口。window.open()
方法打开的,否则window.opener
可能为null
或未定义。通过这种方式,你可以在关闭子窗口的同时刷新父窗口,确保父窗口的数据是最新的。
领取专属 10元无门槛券
手把手带您无忧上云