【问题标题】:Window.open not displaying anything after adding iframe tag添加 iframe 标记后,Window.open 不显示任何内容
【发布时间】:2015-08-21 19:49:26
【问题描述】:

我正在尝试使用带有动态内容的 window.open 打开一个新窗口(对于打印功能,我正在使用此动态内容)。 在window.open 页面上看不到下面的动态 HTML,因为在查看源代码中它是可用的。请帮我看看为什么它没有在那里显示。

下面是代码。

var win = window.open('', 'title', 'toolbar=0,location=0,menubar=0,resizable=yes,width=' + (screen.width - 100) + ',   height=' + (screen.height - 150));

win.document.write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");

win.document.write("<html>");
win.document.write("<head><title>title</title>");
win.document.write('<script language="javascript" type="text/javascript">function printPage() { PrintDiv("defaultPrintBuffer"); }<\/script>');
win.document.write('</head>');

win.document.write('<body>');

win.document.write("<iframe  width='560' height='315' id='defaultPrintBuffer2' name='defaultPrintBuffer2'>");
win.document.write(iframeContent);
win.document.write("</iframe>");
win.document.write('</body>');

win.document.write("</html>");

win.document.close();

win.focus();
win.printPage();

【问题讨论】:

  • 您可以将您正在创建的新页面的所有静态部分放在一个单独的 html 文件中并打开该文件。这样您就不必使用 document.write 并且可以以正常方式设置 iframe 的 url 或内容。但要回答您的问题,您的脚本标签未正确关闭:&lt;\/script&gt;
  • 我已经使用jquery生成了iframe,iframe src中没有url。我正在实现打印功能并尝试使用 IFrame 来实现。

标签: javascript jquery html css iframe


【解决方案1】:

既然您提到您正在尝试实现打印,我将在答案而不是评论中添加我是如何解决这个问题的,因此代码更具可读性。 基本上,我创建了一个空的(但有效的)html 页面,并在打印之前将节点插入该页面。这避免了使用 document.write 和 iframe,这在很多情况下被认为是不好的做法。如果您真的想使用 iframe,只需将 iframe 添加到打印页面 html 并将您的内容附加到该节点而不是正文。

var data = $('myPartOfPageSelector'),
    printPage;
if (!data || !data.length) alert('Nothing to print.');
else {
    printPage = window.open('resources/print.html');
    setTimeout(function() {
        printPage.document.body.innerHTML = data.innerHTML;
        printPage.print();
        printPage.close();
    }, 100);
}

【讨论】:

  • 非常感谢这个解决方案,它似乎可以工作,但请建议我如何在 print.html 中添加 iframe,因为我将打印 iframe 不完整页面。
  • 这是完美的答案。非常感谢。
【解决方案2】:

iframe 标签不显示您放入其中的内容,您必须在 iframe 中加载页面。

您可以使用脚本将内容放入 iframe:

win.document.write("<iframe  width='560' height='315' id='defaultPrintBuffer2' name='defaultPrintBuffer2'>");
win.document.write("</iframe>");
win.document.write("<script type='text/javascript'>var doc = document.getElementById('defaultPrintBuffer2').contentWindow.document;doc.open();doc.write('" + iframeContent.replace("'","\\'").replace("\\","\\\\") + "');doc.close();</script>");

请注意,内容本身应该是一个完整的 HTML 文档。

【讨论】:

  • 它抛出一个错误 TypeError: doc.write is not a function
  • @user2078643:我错过了最后的 .document 从窗口获取文档对象。我更新了上面的代码。
猜你喜欢
  • 2022-07-31
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 2012-09-26
  • 2018-01-05
相关资源
最近更新 更多