如题,layui 的表格打印的方式是将表格的数据重新组合成一个新页面,但是只能打印当前页面的内容,讲真不够用,找了一上午找了一些说是自己改的,但是都不满意,没什么用,还是只能打印当前页的内容,我的想法是写一个函数,传递显示的列和需要打印的数据,直接打印。就像某些同学要的那种打印全部数据吧。废话不多说了,直接上代码吧。
var cols = [[ {type: 'checkbox'} ,{field:'id', title:'ID'} ,{field:'title', title:'标题'} ,{field:'short_title', title:'短标题'} ,{field:'keyword', title:'关键字'} ,{field:'seo_title', title:'seo标题'} ,{field:'seo_keyword', title:'seo关键字'} ,{field:'thumbnail', title:'缩略图'} ,{field:'date', title:'显示时间'} ,{field:'views', title:'观看次数'} ,{field: 'sort', title:'排序'} ,{field: 'create_time', title:'创建时间'} ,{field: 'lb', title:'类别'} ,{field: 'zhiding', title:'置顶'} ,{title:'操作', toolbar: '#barDemo'} ]]; table.on('toolbar(table)',function(obj){ if(obj.event == 'LAYTABLE_TIPS')(obj.event == 'print2'){ $.ajax({ url:'/admin/articleAll', type:'get', success:res=>{ print(res,cols) } }) } }) function print (res,cols) { var v = document.createElement("div"); var f = ["<head>", "<style>", "body{font-size: 12px; color: #666;}", "table{width: 100%; border-collapse: collapse; border-spacing: 0;}", "th,td{line-height: 20px; padding: 9px 15px; border: 1px solid #ccc; text-align: left; font-size: 12px; color: #666;}", "a{color: #666; text-decoration:none;}", "*.layui-hide{display: none}", "</style>", "</head>"].join(""); thead = `<h1 style="text-align: center;">这是标题</h1><table><thead><tr>` for(let v2 of cols[0]){ if((v2.type == 'checkbox') || v2.hasOwnProperty('toolbar')){ thead += `<th class="layui-table-col-special">空列</th>` }else{ thead += `<th>${v2.title}</th>` } } thead += `</tr></thead></table>` $(v).append(thead); var tr = `<tbody>` for(let v of res){ tr += '<tr>' for(let v2 of cols[0]){ if((v2.type == 'checkbox') || v2.hasOwnProperty('toolbar')){ tr += `<td class="layui-table-col-special"></td>` }else{ var field = v2.field ?? 'id' tr += `<td>${v[field]}</td>` } } tr += '</tr></tbody>' } $(v).find('tr').after(tr) $(v).find("th.layui-table-patch").remove(); $(v).find(".layui-table-col-special").remove(); var h = window.open("打印窗口", "_blank"); h.document.write(f + $(v).prop("outerHTML")); h.document.close(); h.print(); h.close(); }