简体   繁体   English

无法使用Javascript打印div的内容

[英]Unable to print div's content using Javascript

I'm trying to print the content of a div when the "Print" button is clicked. 单击“打印”按钮时,我正在尝试打印div的内容。 I keep getting this error: "Unable to set value of the property 'innerHTML': object is null or undefined." 我不断收到此错误:“无法设置属性'innerHTML'的值:对象为null或未定义。” I read some posts over the Internet but I still can't find a working solution. 我通过Internet阅读了一些帖子,但是仍然找不到有效的解决方案。

Here is my javascript code I use to print (got from here ): 这是我用来打印的JavaScript代码(从此处获取 ):

<script type="text/javascript">
    function printDiv(divName) {
        var printContents = document.getElementById(divName).innerHTML;
        var originalContents = document.body.innerHTML;

        document.body.innerHTML = printContents;

        window.print();

        document.body.innerHTML = originalContents;
    }
</script>

My button event raises here: 我的按钮事件在这里引发:

<asp:Button ID="ButtonPrint" runat="server" Text="Print »" OnClientClick="printDiv('content');return false"></asp:Button>

And this is the div I'm supposed to print: 这是我应该打印的div:

 <div id="content" runat="server">
    <h1 class="title" runat="server" id="formulario"></h1>
    <asp:Table ID="TableForm" runat="server"></asp:Table>
    <div id="TableQuest" runat="server">
    </div>
    <asp:Table ID="TableText" runat="server"></asp:Table>
   <asp:Label ID="LabelInfo" runat="server" Text=""></asp:Label>
</div>   

Any help would be greatly appreciated! 任何帮助将不胜感激!

Thanks to @ Evan Knowles I finally found a solution. 感谢@ Evan Knowles,我终于找到了解决方案。

I'm actually using a MasterPage and Content Pages, so my id's name 'content' is automatically changed in 'ContentPlaceHolder1_content'. 我实际上使用的是MasterPage和Content Page,因此我的ID名称“ content”会在“ ContentPlaceHolder1_content”中自动更改。

If the method is called using the new generated id: <asp:Button ID="ButtonStampa" runat="server" Text="Stampa »" OnClientClick="printDiv('ContentPlaceHolder1_content');return false"></asp:Button> everything works just fine! 如果使用新生成的ID调用该方法: <asp:Button ID="ButtonStampa" runat="server" Text="Stampa »" OnClientClick="printDiv('ContentPlaceHolder1_content');return false"></asp:Button>一切正常!

You should use - <%=content.ClientID()%> 您应该使用- <%=content.ClientID()%>

your Div is server side so you will not get this div as you mention in your question. 您的Divserver side因此您不会像在问题中提到的那样获得此div You have to use .ClientID as below code. 您必须使用.ClientID作为以下代码。

document.getElementById('<%=content.ClientID %>').innerHTML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM