首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用HTML打印表

用HTML打印表
EN

Stack Overflow用户
提问于 2022-05-09 09:26:46
回答 3查看 660关注 0票数 0

我已经在我的网页中删除了一个表格,我想把它打印在按钮上,点击.My按钮不工作,我的代码如下所示。

代码语言:javascript
复制
<button id="button1">Print me</button>  
                        
    <table id="printTable" class="display responsive-table " style=" margin-bottom:50px; border-radius: 4px;"  >
    <thead>
    <tr >
    <th>Sl.No.</th>
    <th>Description</th>
    <th>Balance</th>
    
    </tr>
    </thead>
    <tbody>
    
    <script>
    function printData()
    {
        var divToPrint=document.getElementById("printTable");
        newWin= window.open("");
        newWin.document.write(divToPrint.outerHTML);
        newWin.print();
        newWin.close();
    }

    $('#button1').on('click',function(){
    printData();
    })
    </script>
EN

回答 3

Stack Overflow用户

发布于 2022-05-09 09:34:35

如果不使用jquery,请执行以下操作:

代码语言:javascript
复制
        function printData() {
            var divToPrint = document.getElementById("printTable");
            newWin = window.open("");
            newWin.document.write(divToPrint.outerHTML);
            newWin.print();
            newWin.close();
        }

        const btn = document.getElementById("button");
        btn.addEventListener('click', () => printData())

此外,还必须关闭所有标记(表,tbody.)

票数 0
EN

Stack Overflow用户

发布于 2022-05-09 09:42:50

请使用下面的代码。我已经注释掉了newWin.close()函数,所以您将看到结果。

代码语言:javascript
复制
<button id="button">Print me</button>   
                        
    <table id="printTable" class="display responsive-table " style=" margin-bottom:50px; border-radius: 4px;"  >
    <thead>
    <tr >
    <th>Sl.No.</th>
    <th>Description</th>
    <th>Balance</th>
    
    </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
    
    <script>
    function printData()
    {
      
        var divToPrint=document.getElementById("printTable");
        newWin= window.open("");
        newWin.document.write(divToPrint.outerHTML);
        newWin.document.close();
        newWin.print();
        //newWin.close();
    }

    document.querySelector("#button").addEventListener("click", function(){
      printData();
    });
    
    </script>
票数 0
EN

Stack Overflow用户

发布于 2022-05-09 09:30:00

你没有关闭表标签。取而代之的是一个开头的tbody标记。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72169720

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档