1

我不知道为什么,但是当我单击打印按钮时,打印预览总是显示标签选择选项上的第一个选项

例如: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() 函数,它将打印整个页面,我只想打印我选择的内容

谢谢你的帮助,

4

2 回答 2

2

更改选择框的值并不会真正改变 dom 树。您可以强制它更改 dom 树。只需在您选择的 onchange 中添加一些 javascript

 <select onchange="this.options[this.selectedIndex].setAttribute('selected','selected');">
     <option>-</option>
     <option>A</option>
     <option>B</option>
 </select>

然后,innerHTML 将是<option selected="selected">A</option>

于 2013-04-17T21:12:00.107 回答
0

给你的<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变量中。

于 2013-04-17T20:54:34.953 回答