javascript - 从子窗口调用父窗口函数不起作用

标签 javascript html

我有两个 HTML同一目录下的文件:

parent.html

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript">
function open_child_window() {
    var sayHello = function(name) {
        alert('Hello ' + name + '!');
    }
    var win = window.open('child.html');
    win.onload = function() {
        win.myCallbackFunction = sayHello;
    };
}
</script>
</head>
<body>
    <a href="#" onclick="open_child_window();">Open Child Window</a>
</body>
</html>

child.html

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript">
function sayHelloParent() {
    myCallbackFunction('Susan');
}
</script>
</head>
<body>
    <a href="#" onclick="sayHelloParent();return false;">Say Hello on the Parent Window</a>
</body>
</html>

使用上面的两个代码,我点击:Open Child Window在父窗口上。然后,当我单击链接时:Say Hello on Parent Window从子窗口,我在父窗口上收到带有正确消息的警报。

现在,我的目标是无需单击该链接即可自动完成此操作。

我尝试了不同的方式,比如 <body onload="..." ...>等,但没有成功。

关于如何让这项工作有任何想法吗?

谢谢!

最佳答案

在页面加载时调用回调的问题是回调甚至还没有添加到子窗口,您可以添加一个 setTimeout 等待一小段时间直到函数被添加。

这是因为 parent.html 的代码在页面内容加载之后运行,而且在加载时运行其代码之后。

document.addEventListener('DOMContentLoaded', function() {
    setTimeout(function() {
        myCallbackFunction('Susan');
    }, 10)
});

我用的是addEventListener函数而不是onLoad,它们应该有相同的功能

关于javascript - 从子窗口调用父窗口函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50786039/

相关文章:

javascript - 将 `new` 和 `()` 与 require 一起使用

javascript - 如何更新 meteor.js 中的 Mongodb 集合?

javascript - 事件委托(delegate) : catch event on Element not its children

javascript - 如何使用 Python 触发从网站下载文件?

javascript - 通过 AJax 传递变量

javascript - 选择父 ID 始终返回未定义

php - 在 .JSP 中内联 PHP?

jquery - 居中、裁剪、使视频背景(在 iframe 中)适合父元素

jquery - 灯箱叠加层未在 Chrome 上显示,但在 Chrome Canary 上运行良好

javascript - 实时预览与代码扩展