更改弹出窗口内容

4
我使用popup = window.open(....)打开了一个弹出窗口,然后试图将一些HTML插入到弹出窗口中的一个div中。popup.document.getElementById('div-content').innerHTML = "hello world";不起作用,但是popup.document.getElementById('the-field').value = "Hello There";可以更改带有id="the-field"的字段内容。 有什么想法为什么一个有效而另一个无效?我该怎么替换div的内容? 希望你可以帮忙。 编辑: 弹出窗口
<!DOCTYPE html>
<html>
   <head>
        <title>Report</title>
        <meta charset="utf-8">
   </head>

    <body>
        <header>

        </header>

        <div id="div-content"></div>

        <div id="report-container">
            <input type="text" id="the-field" name="the_field"/>
        </div>

        <footer>
        </footer>

     </body>

 </html>  

代码

  function reportComplete(report_content)
  {
  var popup;
  var template_path;

  template_path = base_url + "application/views/secure/reports_preview.php";
  popup = window.open(template_path, "Report", "scrollbars=yes ,resizable=yes");

  popup.document.getElementById('the-field').value = "Hello There"; // this works

  popup.document.getElementById('div-content').innerHTML = "hello world";

  }

1
你可以把代码发布到主页和弹出窗口中吗? - Chris Pietschmann
2个回答

5
或者简单地说:
<script type="text/javascript">    
function reportComplete(report_content)
{
    var popup;
    var template_path;

    template_path = base_url + "application/views/secure/reports_preview.php";
    popup = window.open(template_path, "Report", "scrollbars=yes,resizable=yes");

    popup.window.onload = function() {
        popup.document.getElementById('the-field').value = "Hello There";
        popup.document.getElementById('div-content').innerHTML = "hello world";
    }
}
</script>

3
我认为问题在于当您尝试访问弹出窗口中的某个部分时,该文档尚未完成加载。在我的机器上,提供的代码无法访问任何一个div。
如果您要插入的内容是固定的,则只需在弹出窗口页面上进行所有这些更改,以便仅在文档完全加载时才能实现它。如果您需要发送一些动态内容,则最简单的方法可能是使用查询字符串。
更新: 有一种方法可以在弹出窗口完成加载后仅触发DOM操作函数。首先,在主窗口上需要一个回调函数,并将所有DOM操作代码放在其中:
window.callback = function(doc) {
    doc.getElementById('the-field').value = "Hello there";
    doc.getElementById('div-content').innerHTML = "Hello world";
}

然后,在弹出窗口上,只需将函数调用绑定到body onload事件上:

<script type="text/javascript">
    function loaded() {
       window.opener.callback(document);
    }
</script>
<body onload="loaded();"><!-- body content --></body>

你说得对!这是一个时间问题。如果我在 popup.document.getElementById('the-field').value = "Hello There"; 上设置断点,那么两个调用都会成功。div 和字段都可以更新。现在的问题是如何知道弹出窗口何时准备好进行操作? - djeetee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接