如何从子窗口jquery调用父窗口函数?

Nat*_*sha 19 javascript jquery html5

我只需要在用户关注子窗口时调用父窗口中的函数.我在父窗口中有这个代码,

<html> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script language="Javascript" type="text/javascript">
        function CallParent()
        {
            alert(" Parent window Alert");
        }
    </script>
    <body> 
        <a href="javascript:void(0);" NAME="My Window Name" title=" My title here " onClick=window.open("child.html","Ratting","width=550,height=170,0,status=0,");>Click here to open the child window</a>
    </body> 
</html>
Run Code Online (Sandbox Code Playgroud)

和贝娄代码在我的孩子的窗口,

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script language="Javascript" type="text/javascript">
            jQuery(document).ready(function(){  
                window.opener.CallParent();
            });
        </script>
    </head>
    <body> 
        <h2>This is Child window</h2> 
    </body> 
</html>
Run Code Online (Sandbox Code Playgroud)

所以..在这种情况下,我认为CallParent()将在子窗口打开后才会被触发.但似乎没有用.可以任何人给我任何提示,使这个脚本工作,或任何更好的方式来做到这一点.

Kha*_*lid 17

用这个

window.parent.CallParent();
Run Code Online (Sandbox Code Playgroud)

代替

window.opener.CallParent();
Run Code Online (Sandbox Code Playgroud)

window.parent 保存对当前窗口或子帧的父级的引用.

如果窗口没有父级,则其parent属性是对自身的引用.

当在一个被加载的窗口<iframe>,<object>或者<frame>,它的父是与元件嵌入窗口的窗口.

参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/parent

  • 它真的有效吗?我试图使用这种方法无济于事 - 我收到以下错误:window.parent.CallParent()不是一个函数... (3认同)
  • 虽然这可能会解决问题,但您应该为您的答案提供一些解释,并且可能还包括指向资源的链接,您可以在其中找到有关该问题的更多信息。 (2认同)

dee*_*akb 12

尝试以下内容:

parent.html

<html> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script language="Javascript" type="text/javascript">
        window.CallParent = function() {
            alert(" Parent window Alert");
        }
    </script>
    <body> 
        <a href="javascript:void(0);" NAME="My Window Name" title=" My title here " onClick=window.open("child.html","Ratting","width=550,height=170,0,status=0,");>Click here to open the child window</a>
    </body> 
</html>
Run Code Online (Sandbox Code Playgroud)

child.html

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script language="Javascript" type="text/javascript">
            jQuery(document).ready(function(){  
                opener.CallParent();
            });
        </script>
    </head>
    <body> 
        <h2>This is Child window</h2> 
    </body> 
</html>
Run Code Online (Sandbox Code Playgroud)

您不应该在父项上执行此操作,否则opener.CallParent()将无效,执行window.CallParent使CallParent可用作窗口范围:

function CallParent() {
  alert(" Parent window Alert");
}
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地打电话给opener.CallParent();window.opener.CallParent();.