单击打印按钮时打印动态生成的数据 - 表有一个 ID,但表数据(td 和 tr)数据是动态生成的。
我能够获取表中的数据,并且我尝试使用 window.print java 脚本打印所有内容。
HTML 代码 -
<div class="panel-body">
<table class ="table table-hover" id="TableData">
<caption>Representative Report</caption>
<thead>
<th>Date</th>
<th>Doctor's Name </th>
<th>Sampling Tablets </th>
<th>Samling Quantity</th>
<th>Chemists</th>
<th>POB</th>
<th>Location</th>
<th>Area</th>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
Ajax 调用在表中生成报告 -
for (element in data)
{
var productsArray = data[element].products.split(',');
var quantityArray = data[element].quantity.split(',');
var chemistArray = data[element].Retailername.split(',');
var pobArray = data[element].Pob.split(',');
// find the largest row number
var maxRows = Math.max(productsArray.length, quantityArray.length, chemistArray.length, pobArray.length);
var content = '';
var date = '<td rowspan="' + maxRows + '">' + data[element].date + '</td>';
var doctorName = '<td rowspan="' + maxRows + '">' + data[element].doctor_name + '</td>';
var locations = '<td rowspan="' + maxRows + '">' + data[element].locations + '</td>';
var area = '<td rowspan="' + maxRows + '">' + data[element].area + '</td>';
content += '<tr>' + date + doctorName;
for (var row = 0; row < maxRows; row++) {
if (row !== 0) {
content += '<tr>';
}
// the ternary operator is used to check whether there is items in the array
// if yes, insert the value between the <td></td> tag
// if not, just add an empty <td></td> to the content as a placeholder
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>';
content += '<td>' + (quantityArray[row] ? quantityArray[row] : '') + '</td>';
content += '<td>' + (chemistArray[row] ? chemistArray[row] : '') + '</td>';
content += '<td>' + (pobArray[row] ? pobArray[row] : '') + '</td>';
if (row === 0) {
content += locations + area + '</tr>';
} else {
content += '</tr>';
}
}
$('#tbody').append(content);
}
},
这里我将所有 td 和 tr 添加到表中
当单击打印按钮时,我只想打印表中假定的某些列(日期、医生姓名和化学家姓名)。
我可以使用 Onclick="Window.print"但这会打印整个页面或整个表格。
任何帮助将不胜感激。
最佳答案
您可以使用 css 来实现此目的。只需定义要隐藏的列即可。 这是一个示例。我隐藏了第二列和最后一列。希望能有所帮助,新年快乐,我的 friend :))
<style>
@media print {
table td:last-child {display:none}
table th:last-child {display:none}
table td:nth-child(2) {display:none}
table th:nth-child(2) {display:none}
}
</style>
<div class="panel-body">
<table class ="table table-hover" id="TableData">
<caption>Representative Report</caption>
<thead>
<th>Doctor's Name</th>
<th>Chemists</th>
<th>POB</th>
<th>Location</th>
<th>Area</th>
</thead>
<tbody id="tbody">
<tr>
<td>Iron Man</td>
<td>ABC</td>
<td></td>
<td>China</td>
<td>Asia</td>
</tr>
<tr>
<td>Captain</td>
<td>XYZ</td>
<td></td>
<td>England</td>
<td>Europe</td>
</tr>
</tbody>
</table>
</div>
<button id="btnPrin" onclick="window.print();">Print</button>
关于javascript - 动态数据打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54050122/