如題,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(); }