更改弹出内容

时间:2011-09-13 03:24:29

标签: javascript popup

我正在使用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";

  }

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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>
相关问题