[Javascript] Calling the Printer from a Web Page

Some people reported that clicking doesn’t respond. I’ve tested this on both Chrome and IE and it works:

QQ截图20180824093826

I think the likely reason is that jQuery was not included. I’ve now added jQuery from a CDN and updated the code to:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<html>
<head>
    <meta charset="utf-8">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
    <title></title>
</head>
<body>
    <div id='div1'>Put the content to print here</div>
    <div id="div2">div2 content</div>
    <a href="javascript:printHTML('#div1')" target="_self">Print</a>
    <script language="javascript">
        function printHTML(page) {
            var bodyHTML = window.document.body.innerHTML;
            window.document.body.innerHTML = $(page).html();
            window.print();
            window.document.body.innerHTML = bodyHTML;
        }
    </script>
</body>
</html>

Original Javascript code, requires jQuery:

1
2
3
4
5
6
function printHTML(page) {
    var bodyHTML = window.document.body.innerHTML;
    window.document.body.innerHTML = $(page).html();
    window.print();
    window.document.body.innerHTML = bodyHTML;
}