单击"打印"按钮时,不会打印"选择"选项中的值



我已经编写了一个javascript按钮来打印页面中的所有HTML。当我点击相同的时,除了选择时的option值外,所有打印都很好。下面是代码片段。

问题的实时演示:

https://codepen.io/T9-T9/pen/VwLKbOv

因此,在演示中,如果您将选项从"a"更新为"b"或其他,并单击"打印结果",它仍然会打印默认的"a",而不是您选择的内容。代码段如下。

HTML:

<div class="container" id="printcontent">
<div class="row">
<div>
<h4>Title here</h4>
<form>
<fieldset>
<label class='life_area'>01</label>
<select id='01'>
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">d</option>
</select>
<label class='life_area'>02</label>
<select id='02'>
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">d</option>
</select>
</fieldset> 
</form>         
</div>
</div>
</div>
<div id="print-content">
<form>
<input type="button" class="print-result" onClick="PrintElem('print-content')" value="print result"/>
</form>
</div>

JavaScript:

function PrintElem(elem)
{
var mywindow = window.open('', 'PRINT', 'height=800,width=2200');
mywindow.document.write('<html><head>');
mywindow.document.write('</head><body>');
mywindow.document.write(document.getElementById('printcontent').innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); 
mywindow.focus();       
setTimeout(function () {
mywindow.print();
mywindow.close();
}, 1000)
return true;
}

我进行了多次更新,但无法修复此部分。

元素的innerHTML将仅检索HTML标记-它不会检索可能不在HTML中的元素的状态。例如,当选择发生更改时,不会更改HTML标记。(类似地,既不将文本放入输入框,也不添加事件侦听器(。

在这种情况下,您可以遍历所选的选项,并为它们提供selected属性,该属性将反映在HTML标记中(因此可以正确检索(。selected属性将导致在页面加载上选择有问题的选项:

for (const option of document.querySelectorAll('option:checked')) {
option.setAttribute('selected', '')
}
mywindow.document.write(document.getElementById('printcontent').innerHTML);

最新更新