首先我要指出的是,我的主模块带有一个动态填充 <div id='printableArea'></div>
的下拉列表。 。在此 div 中,动态内容将提供 (1) 打印按钮:<input id='printButton' type='button' value='Print'>
(2) jQuery 将内容输出到空白页进行打印:
$('#printButton').on('click',function(){
printData();
});
function printData() {
var divToPrint = document.getElementById("printableArea");
newWin = window.open("","_blank");
newWin.document.write('<html><head><title></title><style type="text/css">@page { size: portrait; -webkit-print-color-adjust:economy;}' + '</style></head><body>');
newWin.document.write(divToPrint.outerHTML);
newWin.document.write('</body></html>');
setTimeout(function(){
newWin.print();
}, 1000);
return false;
}
它似乎有效,但并非一直有效。单击打印按钮后,将出现一个新窗口,其中包含预期的动态内容,但不会显示打印对话框(在 Chrome 中)。如果我通过下拉菜单切换回主页,然后切换回新窗口,则会显示打印对话框。我猜想一旦主页再次获得焦点,就会触发 setTimeout...我做出这个假设是因为我注意到打印按钮仍然处于焦点状态,就像我单击并按住它一样。
我已经尝试解决这个问题几个小时了,但我已经放弃了。有什么建议吗?
最佳答案
找到了一个解决方法/解决方案...之前曾尝试过,但由于语法错误而失败(因为我使用的是 PHP,所以没有正确转义)。
newWin.document.write('\\x3Cscript>'); // Escaped <script>
newWin.document.write('print();');
newWin.document.write('\\x3C/script>'); // Escaped </script>
-- 感谢 Taplar 再次提出这种方法。
关于使用 AJAX 时 JavaScript 打印失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47823177/