我使用foreach从数据库中获得了一些列表,现在我想按按钮print打印具有“ print” id的所有元素,但是在我的情况下,当我单击print时,我只能打印列表中的第一项,不是全部。
<?php $unos = $db->odradi("SELECT * FROM books WHERE cust='$cust' ORDER BY id ASC");
if (!empty($unos)) {
foreach($unos as $podatak=>$value){
$r_id=$unos[$data]['id'];
?>
<div class="col-xs-12 col-sm-4 col-lg-2" id="print">
<div class="well well-sm bg-color-light txt-color-black text-center">
<small><?php echo $db[$data]['name'] ?></small><br>
<img alt="<?php echo $unos[$data]['name'] ?>" src="barcode.php?codetype=Code39&size=40&text=<?php echo
$unos[$data]['id'] ?>&print=true" />
</div> </div> <?php }
} ?>
<button onclick="printaj()">Print all</button>
还有我的JS:
<script>
function printaj() {
var prtContent = document.getElementById("print");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
</script>
答案 0 :(得分:0)
解决方案1:使用类名而不是ID并遍历类对象:
function printaj() {
var prtContent ;
var content= document.getElementsByClassName("print");
for(var i = 0; i < content.length; i++)
{
prtContent =prtContent +content(i).innerHTML;
}
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
解决方案2:
用id="print"
将所有生成的内容包装在一个div中并打印!
答案 1 :(得分:0)
id必须是唯一的-您创建多个id=print
,而document.getElementById
将返回一个元素
如果它返回多个元素,则您的代码仍将失败,因为您的代码依赖于document.getElementById
返回单个元素的事实!
因此,我建议使用id = print的单个外部div
<?php
$unos = $db->odradi("SELECT * FROM books WHERE cust='$cust' ORDER BY id ASC");
if (!empty($unos)) {
?>
<div id="print">
<?php
foreach($unos as $podatak=>$value){
$r_id=$unos[$data]['id'];
?>
<div class="col-xs-12 col-sm-4 col-lg-2">
<div class="well well-sm bg-color-light txt-color-black text-center">
<small><?php echo $db[$data]['name'] ?></small><br>
<img alt="<?php echo $unos[$data]['name'] ?>" src="barcode.php?codetype=Code39&size=40&text=<?php echo $unos[$data]['id'] ?>&print=true" />
</div>
</div>
<?php
}
?>
</div>
<?php
}
?>
<button onclick="printaj()">Print all</button>
使用此解决方案,无需更改printaj