I have some simple JavaScript code like this:
<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?
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.
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>
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.
来源:https://stackoverflow.com/questions/10569374/how-to-set-the-innerhtml-of-some-element-in-a-window-opened-by-a-javascript-wind