js中打印使用

window.print()这个方法可以调打印 :

下面是写的小例子:

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试打印</title>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css"/>
</head>
<style>
.thead{
    padding: 8px;
    border:1px solid #ccc;
    width: 100px;
}
.tbody{
    border: 1px solid #ddd;
    text-align: center;
    vertical-align: middle;
    padding: 8px;
    line-height: 1.42857143; 
}
</style>
<body>
<table id="table">
    <thead>
        <tr>
            <th class="thead">姓名</th>
            <th class="thead">部门</th>
            <th class="thead">日期</th>
            <th class="thead">状态</th>
            <th class="thead">打印</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="tbody">吴雨臻</td>
            <td class="tbody">民事第一审判庭</td>
            <td class="tbody">2016-06</td>
            <td class="tbody">用户已提交</td>
            <td class="tbody"><button id="btn">打印</button></td>
        </tr>
    </tbody>
</table>

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="bootstrap.min.js"></script>
js代码:

<script type="text/javascript">
$(function(){

    $("#btn").click(function(){
        printTable();
    })

    var printTable = function(){
        var wind = window.open('about:blank', '', ''),
        cont = $("#table").html();
        wind.document.write(
                '<style>@media print{.tbody{word-break: ' + 
                'keep-all;white-space:nowrap;}} @media all{th,td{border:1px solid #000;}' + 
                'table{border-collapse:collapse;width:95%;}}</style><table>'+cont+'</table>'
        );

        wind.print();
    }
});
</script>
</body>
</html>

比较简单,看下就明白了。

疑问的是:js代码写成这样不行:

<td class="tbody"><button id="btn" onclick="printTable()">打印</button></td>
<script type="text/javascript">
$(function(){

    var printTable = function(){
        var wind = window.open('about:blank', '', ''),
        cont = $("#table").html();
        wind.document.write(
                '<style>@media print{.tbody{word-break: ' + 
                'keep-all;white-space:nowrap;}} @media all{th,td{border:1px solid #000;}' + 
                'table{border-collapse:collapse;width:95%;}}</style><table>'+cont+'</table>'
        );

        wind.print();
    }
});
</script>

学习下函数的定义了。知道的朋友解释下吧。


--自己解释下:

var function这种函数是定义了再使用的;是js代码在浏览器中初始化时,必须先定义了再使用;调用这个代码必须在定义之后;

而function xx()这种在浏览器初始化js代码时,定义了并且初始化了,以后就可以拿来用;

上面的代码onclick指向这个function,发现这个函数没有被定义就调用,肯定不行;

--说的好乱,百度吧。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值