[英]Passing div to jquery function and get its innerhtml
我有一个功能来打印div的内容。 让我分享我的aspx标记。
<div>
<div id="printarea" runat="server">
</div>
<asp:Button ID="btnPrint" runat="server" Text="Print Div" OnClick="btnPrint_Click" />
在OnClick事件中,将innerhtml设置为div打印区域。 代码是:
protected void btnPrint_Click(object sender, EventArgs e)
{
string divText = GenerateInPatientBill();// "content you want to print";
printarea.InnerHtml = divText;
ScriptManager.RegisterStartupScript(this, Page.GetType(), "script", "PrintDiv(" + printarea.ClientID + ");", true);
}
我需要将printarea div的clientid传递给javascript函数并将其打印出来。 使用的javascript函数是
function PrintDiv(printarea1) {
alert($("#" + printarea1 + ""));
var printContent = $("#" + printarea1 + "").html();
alert(printContent);
var popupWin = window.open('', '_blank', 'width=300,height=400,location=no,left=200px');
popupWin.document.open();
popupWin.document.write(printContent);
popupWin.document.close();
popupWin.focus();
popupWin.print();
popupWin.close();
}
在第2行收到javascript语法错误。请对此提供帮助。
请尝试以下代码。
function printDiv(DivIdToPrint)
{
var divToPrint= document.getElementById('DivIdToPrint');
var newWin=window.open('','Print-Window','width=100,height=100');
newWin.document.open();
newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){newWin.close();},10);
}
该JavaScript将打开一个包含div内容的新窗口,进行打印,然后关闭该窗口。 最后一行,这是在此处设置超时的必须条件,否则在IE窗口将在打印发生之前关闭。
否则您可以使用jQuery插件
printContent在新打开的窗口中将不可用,因此您将收到此错误。要解决此问题,您只需将div内容或标记传递给新打开的窗口,然后进行打印
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.