如何使用jQuery在文档中打印表内容?

时间:2015-03-06 21:09:20

标签: javascript jquery

如何使用jQuery仅打印文档表?

    <!--panel-->
<div class="panel panel-primary">
    <!-- Default panel contents -->
    <div class="panel-heading">New Order
    <button class="btn btn-sm pull-right btn-default" type="submit">Print Item</button>
    </div>

    <div class="panel-body">
        <!--table-->
        <table class="table table-condensed">
            <thead>
                <tr>
                    <th>#</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Username</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>Mark</td>
                    <td>Otto</td>
                    <td>@mdo</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>Jacob</td>
                    <td>Thornton</td>
                    <td>@fat</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td colspan="2">Larry the Bird</td>
                    <td>@twitter</td>
                </tr>
            </tbody>
        </table>
        <!--end of table-->
    </div>
</div>
<!--end of panel-->

Demo

2 个答案:

答案 0 :(得分:1)

试试这个(demo):

$(function () {
    $('button[type="submit"]').click(function () {
        var pageTitle = 'Page Title',
            stylesheet = '//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css',
            win = window.open('', 'Print', 'width=500,height=300');
        win.document.write('<html><head><title>' + pageTitle + '</title>' +
            '<link rel="stylesheet" href="' + stylesheet + '">' +
            '</head><body>' + $('.table')[0].outerHTML + '</body></html>');
        win.document.close();
        win.print();
        win.close();
        return false;
    });
});

答案 1 :(得分:0)

您可以尝试此功能。将您的表放在具有唯一ID的div中,然后在JQuery中引用它:

<script>function printDiv() {
                    var divName= "<DIV ID HERE>";

                     var printContents = document.getElementById(divName).innerHTML;
                     var originalContents = document.body.innerHTML;

                     document.body.innerHTML = printContents;

                     window.print();

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