javascript - window.print 不适用于由 document.write 呈现的页面

标签 javascript html printing

场景: 我正在创建一个新窗口(新选项卡)并通过 javascript 向其写入 html 标记。 1. 新文件。 2. 将 html 标记写入文档的内容。 3.显示新文档。

我需要做什么: 我基本上需要通过单击按钮、链接或加载来打印一个简单的 HTML 页面(javascript 打印对话框)。 问题是我无法获得任何一种工作方式...只有一个异常(exception)。

(唯一的异常(exception))使用 onload="window.print()"仅在出现新窗口并且我单击刷新时才有效(打印对话框不会在初始创建窗口时显示)。

奇怪的是,即使我在事件点击(href、按钮等)上调用“window.print()”,也没有任何反应。但我知道它不是浏览器,因为这个简单的东西的样本/演示工作得很好。

所以它似乎与我的页面呈现方式有某种关系(在本文的“场景”部分中描述)。

代码: 当我单击“打印”按钮时,我调用它(现在究竟是谁/什么调用它并不重要。但只知道它被调用):

function Print(htmlContent) {
  var printWindow = window.open();
  var printDoc = printWindow.document;
  printDoc.write(htmlContent);

而且我忘记说了:传递给 Print scrip 函数的 HTML (htmlContent) 确实是 Html,但它已经被 XSL 转换了。这是 XSL:

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
    <head>
        <style type="text/css" media="print">
            .noprint{
                    display:none;
                }
        </style>
        <script type='text/javascript'>
            function startPrint(){
                window.print();
            }
        </script>
    </head>

      <body>        
        <div >
            <a id="printButton" href="startPrint();">Print this page</a>
        </div>
        Hello world.
</body>
    </html>
  </xsl:template>
</xsl:stylesheet>

我可以确认 javascript 是否有效,因为如果我将 href="startPrint()"替换为 href="alert('hi')",我确实会收到一个带有该警报的弹出窗口。

最佳答案

我仍然不清楚您实际需要使用这段代码做什么。但是,从中我可以理解并根据可用的引用资料 here ,我已经实现了this .

正如您提到的有关 javascript 打印对话框 onClick of link 的工作正常。但是,我仍然认为这似乎不是您的解决方案。请纠正我的错误。

谢谢。

供引用:w3schools

关于javascript - window.print 不适用于由 document.write 呈现的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4894347/

相关文章:

Javascript Cookie 代码不存储 cookie/读取空 cookie 值?

javascript - 在请求 Cookie header 中发送的子域 cookie,但不存在于 IE JavaScript 的 document.cookie 中

javascript - 如何仅在一页中使用 css?

html - 在 iframe 中将按钮居中

html - 打印样式表+链接

delphi - 使用shellexecute时 "printto"的参数是什么?

JavaScript:如何将多字节字符串数组转换为 32 位 int 数组?

html - pie.htc 没有修复 css3 问题

javascript - Electron :如何通过按钮隐藏/显示<br/>和<hr/>?

c# - UWP 直接从 Windows 应用程序打印而不带打印对话框