打印无效

时间:2016-04-20 11:36:59

标签: javascript jquery ajax

我有一个div包含一些input字段,其值由jQuery提供。 我还复制了一些我发现的代码来打印它们,但是当我按下按钮进行打印时,字段中的值都是空的。

这是我的代码:

<script>
    $(document).ready(function() {
        $('#name').val("Bruce");
        $('#lastname').val("Lee");
        $('#age').val("35");
    });
</script>

<script>
    $(document).ready(function() {
       $("#printhem").click(function(){
           var divContents = $("#printedDiv").html();
           var printWindow = window.open('', '', 'height=700,width=900');

           printWindow.document.write('<html><head><title>PRINTED</title>');
           printWindow.document.write('</head><body >');
           printWindow.document.write(divContents);
           printWindow.document.write('</body></html>');
           printWindow.document.close();
           printWindow.print();
        });
    });
</script>

<div id="printedDiv"
    <input name="name" type="text" id="name">
    <input name="lastname" type="text" id="lastname">
    <input name="age" type="text" id="age">
    <div id="printhem">Print</div>
</div>

2 个答案:

答案 0 :(得分:1)

使用attr()

$(document).ready(function() {
$('#name').attr('value',"Bruce");
$('#lastname').attr('value',"Lee");
$('#age').attr('value',"35");
});

答案 1 :(得分:0)

Fiddle检查这可能会有所帮助

<div id="printedDiv">
    <input name="name" type="text" id="name">
    <input name="lastname" type="text" id="lastname">
    <input name="age" type="text" id="age">

</div>
 <input type="button" value="Print Div Contents" id="prinThm" />


$("#prinThm").click(function(){
           var divContents = $("#name").val();
           var divContents2 = $("#lastname").val();
           var divContents3= $("#age").val();
           var printWindow = window.open('', '', 'height=700,width=900');

           printWindow.document.write('<html><head<title>PRINTED</title>');
           printWindow.document.write('</head><body >');
             printWindow.document.write('<br/>');
           printWindow.document.write(divContents);
            printWindow.document.write('<br/>');
           printWindow.document.write(divContents2);
           printWindow.document.write('<br/>');
           printWindow.document.write(divContents3);
           printWindow.document.write('<br/>');
           printWindow.document.write('</body></html>');
           printWindow.document.close();
           printWindow.print();
        });