【问题标题】:Changing popup content更改弹出内容
【发布时间】:2011-09-13 03:24:29
【问题描述】:

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

  }

【问题讨论】:

  • 你能把代码贴在主机页面和弹出窗口中吗?
  • 我已经编辑了主题并添加了代码。谢谢

标签: javascript popup


【解决方案1】:

...或者简单地说:

<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>

【讨论】:

    【解决方案2】:

    我认为这里的问题是当您尝试访问其中的一部分时,弹出窗口中的文档还没有完成加载。在我的机器上,提供的代码都无法访问任何 div。

    如果您要插入的内容是固定的,那么只需在弹出页面本身上进行所有这些更改,这样您就可以在文档完全加载时才发生。如果您需要发送一些动态内容,最简单的方法可能是使用查询字符串。

    更新: 有一种方法可以仅在弹出窗口完成加载时启动 DOM 操作功能。首先,您需要在主窗口上设置一个回调函数,并将所有 DOM 操作代码放在那里:

    window.callback = function(doc) {
        doc.getElementById('the-field').value = "Hello there";
        doc.getElementById('div-content').innerHTML = "Hello world";
    }
    

    然后,只需将函数调用绑定到弹出窗口上的正文 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 和字段是可更新的。现在的问题是如何判断弹出窗口何时可以被操作?
    猜你喜欢
    • 2017-09-05
    • 2017-09-14
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 2020-06-26
    相关资源
    最近更新 更多