[英]Javascript: Empty html div contents after Window.print()
点击按钮,我使用javascript的window.print()
打印print_div
内容,
但由于一些安全问题,我想避免多次打印(如使用Cntrl + P)选项,所以我想清除print_div
内容,用户无法一次又一次地重新打印。
粗略的代码在这里,
document.getElementById("print_div").innerHTML = //Some contents to be printed on paper.
window.print()
document.getElementById("print_div").innerHTML = '' // Clearing old contents to avoid mis-use
但是这个代码根本不起作用,它在创建打印预览之前清除print_div
内容,就像在chrome中一样。(我猜,异步工作)
谁能告诉我,这里哪里做错了?
注意 :我使用Chrome: 22.0.1229.92 m
来测试我的代码,我只想使用Chrome: 22.0.1229.92 m
。
您可以使用setTimeout方法并尝试它。
setTimeout("your code or function etc",mili seconds)
setTimeout("document.getElementById('print_div').innerHTML = ''",5000);
这是因为没有加载打印窗口。
var showPrintWindow = function (context) {
var printWindow = window.open('', '');
var doc = printWindow.document;
doc.write("<html><head>");
doc.write("<link href='/css/printReport.css' rel='stylesheet' type='text/css' media='print' />");
doc.write("</head><body>");
doc.write(context);
doc.write("</body></html>");
doc.close();
function show() {
if (doc.readyState === "complete") {
printWindow.focus();
printWindow.print();
printWindow.close();
} else {
setTimeout(show, 100);
}
};
show();
};
您正在print_div中打印,并在下一步中清除相同的内容。 因此它显示为空。 您可以将打印数据存储在变量中。 然后在print_div中显示它,您可以清除变量。
var print = "";
print += "<p>Something </p><br/>";
print += "<table><tr><td>Something</td><td>Something</td></tr>
<tr><td>Something</td><td>Something</td></tr> </table>";
document.getElementById("print_div").innerHTML = print;
print = "";
这样的事情。 将此javascript设置为按钮onsubmit事件。
在Chrome中遇到类似的问题,它在“打印预览”中显示空白页面。 尝试使用setTimeout但它不起作用。 什么工作是window.onload。
<div id="printableArea">
<h1>Print me</h1>
</div>
<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
JavaScript的:
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
w = window.open();
w.document.write(printContents);
w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
return true;
}
我不会去setTimeout,它只会在用户立即确认打印时才能工作,你不能盲目地假设...
我会做类似以下的事情:
var html = "<html><head></head><body>" + $("print_div").html() + "</body></html>";
var newWindow= window.open("", "PrintWindow",
"width=100,height=50,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
newWindow.document.writeln(html);
newWindow.document.close();
newWindow.focus();
newWindow.print();
newWindow.close();
然后执行擦除
$('print_div').clear();
setTimeout(function(){printWindow.document.close();
printWindow.print();}, 500);
它会工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.