[英]My page generates multiple divs with same ID and same class. I want to print them all with the same javascript button
So far I managed to print only the first div while using the getElementById() option.到目前为止,我在使用 getElementById() 选项时只打印了第一个 div。 However, since my page generates multiple divs with the same ID it is not possible to print them all with the same print function.
但是,由于我的页面生成了多个具有相同 ID 的 div,因此无法使用相同的打印 function 将它们全部打印出来。 I am looking into the getElementsByClassName() option, but I am not able to get it to print all of the generated divs on the page.
我正在研究 getElementsByClassName() 选项,但我无法让它在页面上打印所有生成的 div。 So far I am getting the "undefined" option.
到目前为止,我得到了“未定义”选项。
Here is my javascript code:这是我的 javascript 代码:
function printFunc() {
var divToPrint = document.getElementById("printableArea");
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += divToPrint.outerHTML;
newWin = window.open("");
newWin.document.write("<h3 align='center'>Print Page</h3>");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
}
Here is how I call it into the page:这是我如何将其调用到页面中的方式:
<input type="button" id="btn" value="Print" onclick="printFunc();">
The I am trying to print is setup like:我要打印的设置如下:
<div id="printableAreaID">
<div class="printArea">
<table>
Contents...
</table>
</div>
</div>
I should maybe mention that this is on Moodle 3.6.2, on a database activity where I have three separate fields to input CSS, javascript and any html I deem necesary, without the need of defining Head and body tags.我也许应该提到这是在 Moodle 3.6.2 上的数据库活动中,我有三个单独的字段来输入 CSS、javascript 和任何 html 我认为不需要定义头部和正文标签。
You should use a class instead of an id however you should be able to use document.querySelectorAll("") to get an array of all the elements with that query.您应该使用 class 而不是 id 但是您应该能够使用 document.querySelectorAll("") 来获取包含该查询的所有元素的数组。
function click() {
var elements = document.querySelectorAll("#printableArea");
elements.forEach((divToPrint) => {
// your code
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.