为什么当您在包含在页面中的 .js 文件中使用 window.parent.showMessage("Video Is OK");
时,它不起作用,但前提是它在页面本身上..?
你能解决这个问题吗?
最佳答案
我可以想到两种情况,您想在哪里使用 window.parent .第一种是当您使用 window.open
打开另一个窗口时。另一个是第一个窗口使用 iframe
加载页面的地方。在前一种情况下,您似乎真的想使用 window.opener。 ,正如 ukostin 所说。在后一种情况下,window.parent
工作正常。无论代码是内联的还是从外部 JS 文件加载的,这两种方法都可以正常工作。以下是一些测试:
弹出窗口
父窗口.htm:
<html>
<head>
<script>function showMsg(msg){alert(msg);}</script>
<body>
<a href="#" onclick="window.open('childWindow.htm','child','width=300,height=100')">Open</a>
</body>
</html>
外部窗口.js:
function showMsgExternal(msg){window.opener.showMsg(msg);}
子窗口.htm:
<html>
<head>
<script>function showMsgInline(msg){window.opener.showMsg(msg);}</script>
<script src="externalWindow.js"></script>
</head>
<body>
<a href="#" onclick="showMsgInline('inline')">Inline</a>
<a href="#" onclick="showMsgExternal('external')">External</a>
</body>
</html>
内嵌框架
父框架.htm:
<html>
<head>
<script>function showMsg(msg){alert(msg);}</script>
</head>
<body>
<iframe src="childFrame.htm" width="300" height="100"></iframe>
</body>
</html>
外部框架.js:
function showMsgExternal(msg){window.parent.showMsg(msg);}
子框架.htm:
<html>
<head>
<script>function showMsgInline(msg){window.parent.showMsg(msg);}</script>
<script src="externalFrame.js"></script>
</head>
<body>
<a href="#" onclick="showMsgInline('inline')">Inline</a>
<a href="#" onclick="showMsgExternal('external')">External</a>
</body>
</html>
关于JavaScript:为什么 windows.parent 会这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2347117/