簡體   English   中英

如何使用jquery / javascript從打印預覽獲取輸入值

[英]How to get input values from print preview using jquery/javascript

我有帶有字段的示例html內容,我需要打印所有內容,包括輸入值,並將其顯示在示例預覽中。 我嘗試使用以下腳本觸發打印:

樣品打印工作正常,但是未顯示輸入值。 我該如何實現? 我應該使用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" /> 

這對我有用-將值復制到value屬性並克隆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");
}

或者

如何使用“打印”按鈕從html頁面僅打印一個div內容

您可以將以下代碼放在PrintPreview函數之前:

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

這樣,就可以在keyup上更改value屬性,並且預覽可以正常工作。

這一次嘗試。

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM