如何在 JavaScript 窗口对象打开的窗口中设置某个元素的 innerHTML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10569374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the innerHTML of some element in a window opened by a JavaScript window object?
提问by RPIBuckHunter
I have some simple JavaScript code like this:
我有一些像这样的简单 JavaScript 代码:
<script type="text/javascript">
function openWindow() {
var mywindow = window.open("file.html");
mywindow.document.getElementById("foo").innerHTML="Hey you!!";
}
</script>
This function is called with an onclick event. The window opens fine, but the element's innerHTML does not change. It is a file I own, so I know I am not being blocked by any security policy, and the element with id 'foo' definitely exists. (It is a DIV). I have tried other variations of .innerHTML like .src and .value, but nothing seems to work. Does anyone have any suggestions?
这个函数是通过一个 onclick 事件调用的。窗口打开正常,但元素的innerHTML 没有改变。这是我拥有的文件,所以我知道我没有被任何安全策略阻止,并且 ID 为 'foo' 的元素肯定存在。(这是一个 DIV)。我尝试过 .innerHTML 的其他变体,如 .src 和 .value,但似乎没有任何效果。有没有人有什么建议?
回答by jmort253
The problem here is that you are most likely trying to access the DOM of the new window before that window has a chance to finish loading.
这里的问题是,您很可能在新窗口有机会完成加载之前尝试访问该窗口的 DOM。
Consider the following:
考虑以下:
<script type="text/javascript">
function openWindow() {
var mywindow = window.open("file.html");
// register an onload event with the popup window so that we attempt to
// modify it's DOM only after it's onload event fires.
mywindow.onload = function() {
mywindow.document.getElementById("foo").innerHTML="Hey you!!";
}
}
</script>
回答by codesurgeon
Just of note... Even after fixing the timing of it you can also have errors with this if you are developing on your local machine instead of on the internet or a local server. I just wasted an hour trying to figure out why it wouldn't work, then uploaded the same code to my server and it worked fine. I was using code that I ran locally 2 years ago but in a different browser, changed a few lines and the browser and it stopped working until running on a server. Hope this helps someone.
请注意......即使在修复它的时间之后,如果您在本地机器上而不是在互联网或本地服务器上开发,您也可能会出现错误。我只是浪费了一个小时试图弄清楚为什么它不起作用,然后将相同的代码上传到我的服务器,它运行良好。我使用的是 2 年前在本地运行的代码,但在不同的浏览器中,更改了几行和浏览器,它停止工作,直到在服务器上运行。希望这可以帮助某人。