如何从弹出窗口javascript中调用带有变量的父窗口jquery函数?

Kum*_*mar 4 javascript jquery

如何从弹出窗口javascript中调用带有变量的父窗口jquery函数?我可以看一下这些简单的例子吗?

Vol*_*erK 5

openerwindow对打开文档的对象的引用.即您可以访问打开窗口的全局javascript命名空间.

例如

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script type="text/javascript">
      function foo(url) {
        // if there is a reference to the opening window
        if (null!=opener) {
          // we call the function in the context of the opening window
          opener.foo(url);
        }
        else {
          // otherwise show the data
          $('#d1').html(new Date() + " : " + url);
        }
      }
    </script>
  </head>
  <body>
    <div id="d1">...</div>
    <button onclick="window.open('?');">new window</button>
    <button onclick="foo(document.URL);">propagte url</button>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果你在(任何)弹出窗口中按下"传播url",函数调用将冒泡到第一个非弹出窗口(具有opener = null).

编辑:请记住,浏览器中实现的安全限制(如跨域检查)适用.

edit2:history.go(0)的示例

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script type="text/javascript">
      function foo() {
        var context = (null!=opener) ? opener : window;
        context.history.go(0);
      }

      $(document).ready( function() {
        $('#d1').html("document ready at "+ new Date());
      });
    </script>
  </head>
  <body>
    <div id="d1">...</div>
    <button onclick="window.open('?');">new window</button>
    <button onclick="foo(document.URL);">...and action</button>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)