简体   繁体   English

如何将onload事件添加到窗口

[英]How to add an onload event to window

My code is, 我的代码是

<html>
    <head>
       <title>onclick test</title>
       <script type="text/javascript">
           var googleWindow = window.open('http://www.google.com');
           window.onload = change;
           function change(){
            alert('Hello');
           }
        </script>
</html>

The above code is working fine. 上面的代码工作正常。 It calls the change function when the window is loading. 加载窗口时,它将调用change函数。 I am trying add onload event to the googleWindow but it is not working. 我正在尝试将onload事件添加到googleWindow,但无法正常工作。

<html>
    <head>
       <title>onclick test</title>
       <script type="text/javascript">
           var googleWindow = window.open('http://www.google.com');
           googleWindow.onload = change;
           function change(){
            alert("Hello');
           }
        </script>
</html>

How do i add an event to the googleWindow? 如何将事件添加到googleWindow?

Thanks, 谢谢,

您不能将事件添加到另一个域中的窗口。

The onload event only triggers a function that is loaded in that window , so you can't really do that. onload事件仅触发在该窗口中加载的函数,因此您实际上无法做到这一点。 However, if you can control the content of the new window you're opening (ie if you'd open a window that displays some content of your own) then you could place an onload handler in the page that opens in that window, and then the called function could interact with the opener window via 'window.opener', eg if you have two files '1.html' and '2.html' then you can have: 但是,如果您可以控制要打开的新窗口的内容(即,如果您要打开一个显示自己的某些内容的窗口),则可以将onload处理程序放置在该窗口中打开的页面中,然后那么被调用的函数可以通过“ window.opener”与打开器窗口进行交互,例如,如果您有两个文件“ 1.html”和“ 2.html”,则可以:

1.html 1.html

<a href="#" onClick="window.open('2.html')">Open '2.html'</a>

2.html 2.html

<head><script>
window.opener.alert("this alert is displayed by the '1.html' window");
</script></head>

In the above, after you click the link in the first window, the second window will open (probably in a new tab in your browser) and immediately after it gets opened you'll see the alert displayed in the first window (ie the first tab) 在上面的窗口中,单击第一个窗口中的链接后,第二个窗口将打开(可能在浏览器的新选项卡中),打开后,您会立即在第一个窗口中看到警报(即第一个窗口)标签)

PS 聚苯乙烯
Oh, and as Rory pointed out in his answer, you must absolutely have the files on the same domain 哦,正如罗里(Rory)在回答中指出的那样,您必须绝对将文件放在同一域中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM