使用javascript在IE 11中打印计算表(交互式表单)



我有不同的交互式表单,我正在寻找一种纯粹的JavaScript解决方案,可以在单击时打印页面的一部分。因此,每个页面都有一个"单击以打印"按钮,并且应该打开一个新页面准备打印。 我尝试了许多解决方案,其中一些解决方案除了IE11之外效果很好。

我的一些表单很复杂,但为了简单起见,以下是我尝试使用的代码的简单示例:

<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
First name: <input type="text" name="firstname" value=""><br>
Last name: <input type="text" name="lastname" value=""><br><br>
Gender: <br />
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other<br><br>
</div> 

<input type='button' id='btn' value='Print' onclick='printDiv();'>

<script type="text/javascript">
function printDiv() {
var divToPrint = document.getElementById('DivIdToPrint').innerHTML;
var newWin = window.open();
newWin.document.write(divToPrint);
newWin.print();
newWin.close();
}
</script>

两个问题: 1. 我无法打印每个表单项的值,并且 2.此解决方案在IE11中不起作用。

有人可以帮忙吗?

  1. 填写表单不会修改 html 标记,也不会更改实际标记中的value属性。所以你不能用.innerHTML获得值。如果您想要带有新值的 html,只需将属性设置为新值即可。
  2. 为了确保脚本的输出实际显示在另一个窗口中,我们应该在编写内容后使用document.close()

您可以查看我的演示,它可以在IE和其他浏览器中运行良好:

<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
First name: <input type="text" name="firstname" value=""><br>
Last name: <input type="text" name="lastname" value=""><br><br>
Gender: <br />
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other<br><br>
<input type="radio" name="aa" value="a"> A<br>
<input type="radio" name="aa" value="b"> B<br>
<input type="radio" name="aa" value="c"> C<br><br>
</div>
<input type='button' id='btn' value='Print' onclick='printDiv();'>
<script type="text/javascript">
function printDiv() {
//Set attribute to new value
var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length - 1; ++index) {
var fieldValue = inputs[index].value;
inputs[index].setAttribute('value', fieldValue);               
}
var radios, i;
radios = document.querySelectorAll('input[type="radio"]:checked');
for (i = 0; i < radios.length; i++) {
radios[i].setAttribute('checked', true);
}
var divToPrint = document.getElementById('DivIdToPrint').innerHTML;
var newWin = window.open();
newWin.document.write(divToPrint);
newWin.document.close(); //Close after writing content
newWin.focus();
newWin.print();
newWin.close();
}
</script>

最新更新