如何在由JavaScript窗口对象打开的窗口中设置某个元素的innerHTML? [英] How to set the innerHTML of some element in a window opened by a JavaScript window object?

查看:116
本文介绍了如何在由JavaScript窗口对象打开的窗口中设置某个元素的innerHTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < script type =text / javascript> 
函数openWindow(){
var mywindow = window.open(file.html);
mywindow.document.getElementById(foo)。innerHTML =Hey you !!;
}
< / script>

使用onclick事件调用此函数。该窗口可以正常打开,但元素的innerHTML不会更改。这是我自己的一个文件,所以我知道我没有被任何安全策略阻止,并且具有ID'foo'的元素肯定存在。 (这是一个DIV)。我尝试了.innerHTML的其他变体,例如.src和.value,但似乎没有任何工作。有没有人有任何建议?

解决方案

这里的问题是,你很可能试图访问新窗口的DOM之前该窗口有机会完成加载。



请考虑以下事项:

 < script type =text / JavaScript的> 
函数openWindow(){
var mywindow = window.open(file.html);

//使用弹出窗口注册一个onload事件,以便我们尝试
//仅在onload事件触发后修改它的DOM。
mywindow.onload = function(){
mywindow.document.getElementById(foo)。innerHTML =Hey you !!;
}

}
< / script>


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>

这篇关于如何在由JavaScript窗口对象打开的窗口中设置某个元素的innerHTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆