我在我的網頁中顯示了一個表格,我想在按鈕單擊時列印它。我的按鈕不起作用我的代碼如下。
<button id="button1">Print me</button>
<table id="printTable" class="display responsive-table " style=" margin-bottom:50px; border-radius: 4px;" >
<thead>
<tr >
<th>Sl.No.</th>
<th>Description</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<script>
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
$('#button1').on('click',function(){
printData();
})
</script>
uj5u.com熱心網友回復:
如果您不使用 jquery,請執行以下操作:
function printData() {
var divToPrint = document.getElementById("printTable");
newWin = window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
const btn = document.getElementById("button");
btn.addEventListener('click', () => printData())
您還必須關閉所有標簽(表格,tbody ..)
uj5u.com熱心網友回復:
請使用以下代碼。我已經注釋掉了 newWin.close() 函式,所以你會看到結果。
<button id="button">Print me</button>
<table id="printTable" class="display responsive-table " style=" margin-bottom:50px; border-radius: 4px;" >
<thead>
<tr >
<th>Sl.No.</th>
<th>Description</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.document.close();
newWin.print();
//newWin.close();
}
document.querySelector("#button").addEventListener("click", function(){
printData();
});
</script>
uj5u.com熱心網友回復:
您沒有結束表格標簽。而是有一個打開的 tbody 標簽。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/471173.html
標籤:javascript html jQuery
