[英]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.