首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

js 关闭子窗体 刷新父窗体

在JavaScript中,关闭子窗口并刷新父窗口通常涉及到window.close()方法和window.opener对象的使用。以下是具体的实现步骤和示例代码:

基本概念

  1. window.close(): 这个方法用于关闭当前窗口。
  2. window.opener: 这个属性指向打开当前窗口的那个窗口对象。

实现步骤

  1. 在子窗口中调用window.close()方法关闭子窗口。
  2. 在子窗口关闭之前,使用window.opener.location.reload()方法刷新父窗口。

示例代码

假设父窗口的HTML文件为parent.html,子窗口的HTML文件为child.html

parent.html

代码语言:txt
复制
<!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>

child.html

代码语言:txt
复制
<!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>

解释

  1. 父窗口
    • 当点击“Open Child Window”按钮时,openChildWindow()函数会被调用,打开一个新的子窗口。
    • window.open()方法的第二个参数是窗口名称,第三个参数是窗口特性(如宽度和高度)。
  • 子窗口
    • 当点击“Close and Refresh Parent”按钮时,closeAndRefreshParent()函数会被调用。
    • window.opener.location.reload()方法会刷新父窗口。
    • window.close()方法会关闭当前子窗口。

注意事项

  • 确保子窗口是由父窗口通过window.open()方法打开的,否则window.opener可能为null或未定义。
  • 在某些浏览器中,出于安全考虑,可能会阻止脚本关闭非脚本打开的窗口。

通过这种方式,你可以在关闭子窗口的同时刷新父窗口,确保父窗口的数据是最新的。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券