我想只打印属于某个类的html文件。我设法创建了getElementById
funciotn,但我似乎无法为getElementsByClassName
创建相同的内容。我需要能够只打印具有class =“print”的单个div,而atm我只打印ID。
以下是我的html代码示例:
<div id="CCC" title"Checklist">
<h2>Checklist</h2>
<div>Content</div>
</div>
<div id="BBB" title="Chapter 1">
<h2 class="Chapter">Chapter 1</h2>
<div><p>Content 2</p></div>
<div>
<table id="Ch1_tab" width="100%" border="1" style="border-color:#D2D2D2; border-collapse:collapse;">
<div id="Q0101" class="print">
<tr>
<td width="41" align="left" valign="top"><div class="QNumber">1.1</div></td>
<td><div class="QText">Name of the vessel:</div></td>
<td width="300"><div class="Response"><input name="Text" type="text" id="vslName" size="31"></div></td>
</tr>
</div>
<div id="Q0102">
<tr>
<td width="41" align="left" valign="top"><div class="QNumber">1.2</div></td>
<td><div class="QText">Vessel IMO Number:</div></td>
<td width="300"><div class="Response"><input name="Text" type="number" id="IMONum" size="10"></div></td>
</tr>
</div>
<div id="Q0107" class="print">
<tr>
<td width="41" align="left" valign="top"><div class="QNumber">1.7</div></td>
<td><div class="QText">How many Load Lines certificates available:</div></td>
<td width="300"><div class="Response"><input name="Text" type="number" id="R0107" size="10"></div></td>
</tr>
</div>
<div id="Q0107" class="print">
<tr>
<td width="41" align="left" valign="top"><div class="QNumber">1.9</div></td>
<td><div class="QText">Date the crew commenced preparation for vetting:</div></td>
<td width="300"><div class="Response"><input name="GenDate" class="GenDate" type="text" id="R0109"></div></td>
</tr>
</div>
</table>
</div>
<iframe name=print_frame width=0 height=0 frameborder=0></iframe>
<p>
<input type="button" value="Print Div" onclick="javascript:printDiv()">
</p>
这是我的JS打印ID =“BBB”
<script>
printDivCSS = new String ('')
function printDiv() {
window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById('BBB').innerHTML
window.frames["print_frame"].window.focus()
window.frames["print_frame"].window.print()
}
</script>
提前致谢!
答案 0 :(得分:1)
getElementsByClassName
返回一堆元素
你必须在for循环中打印每个div
var elems = document.getElementsByClassName("print");
for ( var i = 0; i < elems.length; i++ ) {
window.frames["print_frame"].document.body.innerHTML=printDivCSS+elems[i].innerHTML;
window.frames["print_frame"].window.focus()
window.frames["print_frame"].window.print()
}
答案 1 :(得分:1)
您可以使用document.getElementsByClassName()
或document.querySelectorAll()
轻松完成此操作。下面是一个示例函数,它使用document.querySelectorAll()
查找具有“print”类的所有div:
var visitAllPrintDivs = function(visitFunction) {
var divsWithPrintClass = document.querySelectorAll('div.print');
for (var i = 0; i < divsWithPrintClass.length; i++) {
var divWithPrintClass = divsWithPrintClass[i];
visitFunction(divWithPrintClass);
}
};
...你可以非常简单地使用它:
visitAllPrintDivs(console.log); // applies "console.log(div)" to the divs.