2009-12-10 97 views
4

如何從彈出窗口JavaScript調用帶有變量的父窗口jquery函數?我可以看的任何簡單的例子?如何從彈出窗口javascript調用父窗口jquery函數的變量?

+0

什麼樣的變數你傳球?選擇? html字符串?功能? DOM元素(ouch)? – 2009-12-10 05:04:21

+0

父母。$(某事)有效嗎?似乎應該。 – stimms 2009-12-10 05:07:16

+0

只是一個從popupwindow到父窗口函數的字符串。 – Kumar 2009-12-10 05:09:18

回答

5

opener是參考window對象的開頭文檔。即您可以訪問打開窗口的全局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> 

如果按在(任何)的函數調用將冒泡到第一非彈出窗口(具有開瓶器= NULL)彈出窗口「傳播URL」。

編輯:請記住,在瀏覽器中實施的安全限制(如跨域檢查)適用。

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> 
+0

謝謝。 只需添加「opener.history.go(0);」之前「opener.foo(url);」 ,現在它不工作(對我來說),任何建議。 – Kumar 2009-12-10 06:49:06

+0

是的,我正在更改彈出窗口中的一些主窗口內容,所以我希望它重新載入編輯的內容,並使用history.go(0)恢復與以前相同的頁面視圖。 – Kumar 2009-12-10 07:58:38

+0

我想我可能需要當主窗口重新加載完成時,以便我可以調用它(主窗口)中的jQuery。我試着用window.parent.onload = function_name;但它沒有奏效。任何其他方式? – Kumar 2009-12-10 08:01:44

0
window.opener.jQuery(myVariable); 
+0

感謝您的回覆。我認爲「myVariable」是函數名稱,如果我更正了,如何將變量傳遞給它。如果它是變量如何調用我的函數? – Kumar 2009-12-10 05:11:52

+0

我想象window.opener。$(myVariable)也可以。 – 2009-12-10 05:12:08

+0

也許你需要window.opener.myFunction(someVariable) – 2009-12-10 05:14:00

2

通常你定義一個插件功能是這樣的:

(function($) { // jquery no conflict 

$.fn.myPlugin = function(myvar){ 
    // do something 
} 

})(jQuery); 

然後用這個:

window.opener.$.fn.myPlugin(myvar);