【问题标题】:Add javascript inside print preview page using window.open() method使用 window.open() 方法在打印预览页面中添加 javascript
【发布时间】:2014-02-05 11:42:35
【问题描述】:

我有一个示例fiddle here,其中有一个打印预览按钮。单击该按钮时,它会打开一个新的弹出窗口,该窗口创建为,

function printpage() {
    var data = '<table border="1" cellspacing="0"><tr><td colspan="4">Sample Report</td></tr>' + document.getElementsByTagName('table')[0].innerHTML + '</table>';
    data += '<br/><button onclick="window.print()"  class="noprint">Print the Report</button>';
    data += '<style type="text/css" media="print"> .noprint {visibility: hidden;} </style>';
    myWindow = window.open('', '', 'width=800,height=600');
    myWindow.innerWidth = screen.width;
    myWindow.innerHeight = screen.height;
    myWindow.screenX = 0;
    myWindow.screenY = 0;
    myWindow.document.write(data);
    myWindow.focus();
}

使用谷歌浏览器开发者工具查看源码时,可以得到如下代码。

<html>
<head></head>
<body>
<table border="1" cellspacing="0"><tbody><tr><td colspan="4">Sample Report</td></tr>
    </tbody>
    <tbody>
    <tr><th>Sl.No</th><th>Value 1</th><th>Value 2</th><th>Value 3</th></tr>
    <tr><td>1</td><td>5</td><td>0</td><td>2</td></tr>
    <tr><td>2</td><td>7</td><td>0</td><td>4</td></tr>
    <tr><td>3</td><td>1</td><td>0</td><td>10</td></tr>
    <tr><td>4</td><td>8</td><td>0</td><td>3</td></tr>
    <tr><td>5</td><td>13</td><td>0</td><td>6</td></tr>
</tbody></table><br>
<button onclick="window.print()" class="noprint">Print the Report</button><style type="text/css" media="print"> .noprint {visibility: hidden;} </style>
</body>
</html>

是否可以在该弹出窗口中添加一些额外的 javascript/jquery 代码?

【问题讨论】:

  • 只需将您的脚本添加到data。这是jsFiddle 的示例。请注意结尾 script 标记中的转义 /
  • 感谢@Teemu.. 将其添加为答案,以便我接受。

标签: javascript jquery button printing popupwindow


【解决方案1】:

您可以像这样向data 变量添加脚本:

var data = '<script>/* CODE */ <\/script>' +
    '<table ...>' +
           :
    '<style...>';

字符串中的结尾script 标记必须以某种方式被破坏,这样它就不会显示为文字&lt;/script&gt;。如果是这样,脚本将在找到标记时中断。

您还需要注意,脚本字符串中的引号不会破坏字符串。使用"s 并在需要时使用反斜杠转义'

实际上有更优雅的方式来设置打印页面(或部分页面)的样式,例如,您可以使用Media Querieslink(请参阅media)单独的样式表来设置打印样式。

【讨论】:

  • 我添加了一些脚本here to my sample,但没有工作。我的脚本有什么问题吗?
  • 您的打印窗口永远不会触发$(document).ready(...),因为在write() 之后您还没有关闭它的document。您需要将myWindow.document.close(); 放在document.write() 之后。当您关闭document 时,代码为working fine
猜你喜欢
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
相关资源
最近更新 更多