2016-11-16 23 views
0

我有这个示例html内容的字段 我需要打印所有内容,包括输入值并将其显示在示例预览中。 我试过这个脚本来触发打印:如何从打印预览中使用jQuery/javascript获取输入值

虽然示例打印工作正常,但输入值不显示。我怎样才能做到这一点?我应该使用html()函数以外的其他选择吗?

function PrintPreview() { 
 
    printWindow = window.open("", "", "location=1,status=1,scrollbars=1,width=650,height=600"); 
 
    printWindow.document.write($('#mainbody').html()); 
 
    printWindow.document.close(); 
 
    printWindow.focus(); 
 
}
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> 
 

 
<div id="mainbody"> 
 
    Last Name 
 
    <input type="text" id="lname" name="lname">First Name 
 
    <input type="text" id="fname" name="fname">Middle Name 
 
    <input type="text" id="mname" name="mname"> 
 
</div> 
 
<input type="button" onclick="PrintPreview();" value="Print Preview" />

回答

2

这对我的作品 - 的值复制到值属性和克隆DIV

function PrintPreview() { 
    $("#mainbody > input").each(function() { 
    $(this).attr("value",$(this).val()); 
    }); 

    var printWindow = window.open("", "_blank", "location,status,scrollbars,width=650,height=600"); 
    if (printWindow) { 
    printWindow.document.write($('#mainbody').clone(true)[0].innerHTML); 
    printWindow.document.close(); 
    printWindow.focus(); 
    } 
    else alert("Please allow popups"); 
} 

或者

How to print only one div content from html page using print button

+0

Thanks !.这工作! – Jarich

+0

另外给div一个类,并隐藏除使用打印CSS之外的所有东西 - 然后你不需要打开弹出框 – mplungjan

0

你可以把代码打印预览功能之前,如下所示:

$('input').each(function(){ 
    $(this).keyup(function(){ 
     $(this).attr('value',$(this).val()); 
    }); 
}); 

这样的价值属性上KEYUP改变和预览将正常工作。

-1

这一次尝试。

<div id="mainbody"> 
    Last Name <input type="text" id="lname" name="lname"> 
    First Name<input type="text" id="fname" name="fname"> 
    Middle Name<input type="text" id="mname" name="mname"> 
</div> 
<input type="button" onclick="PrintPreview();" value="Print Preview" /> 
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> 
    <script> 
     function PrintPreview() { 
    window.print(); 
    } 
</script> 
+0

这不是问什么问题 - 这将打印一切,包括打印按钮,除非你隐藏它 – mplungjan