我不知道为什么,但是当我单击“打印”按钮时,打印预览总是在标签选择选项上显示第一个选项
举个例子 :
testingprint.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="printing">
<table>
<tr>
<td>
<select>
<option>-</option>
<option>A</option>
<option>B</option>
</select>
</td>
<td><input type="button" onclick="printPage('printing')"/></td>
</tr>
</table>
</div>
</body>
</html>
和这里的JavaScript:
java.js
<script type="text/javascript">
function printPage(id)
{
var html="<html>";
html+="<head>";
html+="</head>";
html+= document.getElementById(id).innerHTML;
html+="</html>";
var printWin = window.open('','','left=0,top=0,width=1024,height=768,toolbar=0,scrollbars=0,status =0');
printWin.document.write(html);
printWin.document.close();
printWin.focus();
printWin.print();
printWin.close();
}
</script>
为什么即使选择选项“ A”或其他选项,打印预览仍始终显示选项仍为“-”?
谁能给我一些建议?
或者我应该为打印脚本使用什么?
如果我使用print()函数,它将打印整个页面,我只想打印我选择的内容
谢谢你的帮助,
最佳答案
给您的<select>
元素一个id
属性:
<select id="select1">
...
</select>
并使用以下Javascript:
function printPage(id) {
var selectedIndex = document.getElementById("select1").selectedIndex;
var html = "<html>";
html += "<head></head>";
html += "<body>";
html += document.getElementById(id).innerHTML;
html += "<script type='text/javascript'>";
html += "document.getElementById('select1').selectedIndex = " + selectedIndex + ";";
html += "<\/script>";
html += "</body>";
html += "</html>";
var printWin = window.open('','','left=0,top=0,width=1024,height=768,toolbar=0,scrollbars=0,status =0');
printWin.document.open();
printWin.document.write(html);
printWin.document.close();
printWin.focus();
printWin.print();
printWin.close();
}
演示:http://jsfiddle.net/bkHC2/1/
使用
.innerHTML
获取元素的内容时,不会复制有关其当前“状态”的任何内容。因此,我“修复”的快速方法是将Javascript放在新窗口中,该窗口将selectedIndex
元素的<select>
设置为当前在主页上的内容。请注意,我在
<body>
变量中包含了html
元素。
关于javascript - 从标签选择选项打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16069917/