JavaScript:为什么windows.parent是这样的?

时间:2010-02-27 11:18:54

标签: javascript

为什么当您在页面中包含的.js文件中使用window.parent.showMessage("Video Is OK");时,它将无法正常工作,但只有当它位于页面本身时...?

你能解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

尝试使用window.opener作为父窗口的链接。

答案 1 :(得分:0)

我可以想到两种情况,您想要使用window.parent。第一种是当你有一个窗口使用window.open打开另一个窗口时。另一个是第一个窗口使用iframe加载页面的位置。在前一种情况下,似乎你真的想要使用window.opener,正如ukostin所说的那样。在后一种情况下,window.parent工作正常。无论代码是内联还是从外部JS文件加载,这两种方法都能正常工作。以下是一些测试:

<强> POPUP

parentWindow.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>

externalWindow.js:

function showMsgExternal(msg){window.opener.showMsg(msg);}

childWindow.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>

<强> IFRAME

parentFrame.htm:

<html>
<head>
    <script>function showMsg(msg){alert(msg);}</script>
</head>
<body>
    <iframe src="childFrame.htm" width="300" height="100"></iframe>
</body>
</html>

externalFrame.js:

function showMsgExternal(msg){window.parent.showMsg(msg);}

childFrame.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>