[英]How to print array data inside a table
So I have this code where I'm trying to print(physical print as in paper) a table when a button is clicked, which is populated with array data.所以我有这段代码,我试图在单击按钮时打印(纸上的物理打印)表格,其中填充了数组数据。 I managed to print the array data but I can not seem to find on how to put this in a table.
我设法打印了数组数据,但似乎找不到如何将其放入表格中。 also is there a better way than
document.write()
I am not a huge fan of it?还有比
document.write()
更好的方法吗?我不是它的忠实粉丝吗?
var Obj = [];
function printDiv(){
var divContents = document.getElementsByClassName("test")
console.log(divContents)
//if($("div").hasClass("test") == true){// can use jquery hasfind in order to check if acive class exists if yes get content of child divs
//expand if this option is better
//console.log('istrue');
//}
for(var i = 0; i< divContents.length; i++){
Obj.push(divContents[i].textContent +'</br>')
}
var a = window.open('','','height=500,width=500');
a.document.write('<html>');
a.document.write('<body><h1>Div contents are<h1><br>');
a.document.write('<table><tbody><tr>')
a.document.write('<td>'+ Obj.join(' ')+'<td>');
a.document.write('</tr></tbody></table></body></html>');
a.document.close();
a.print();
Obj = [];
}
expected outcome would be:预期结果是:
work order and date are not yet populated this is just a test file to use in a bigger project.工作订单和日期尚未填充,这只是一个用于更大项目的测试文件。
jsfiddle: https://jsfiddle.net/yLz7stxr/ jsfiddle: https://jsfiddle.net/yLz7stxr/
thanks in advance.提前致谢。
I assume we got an array of objects here.我假设我们在这里有一个对象数组。
const dataObject = {'name': null, 'age': null, 'favoriteFood': null}; let data = []; let row = {...dataObject}; row.name = 'John'; row.age = '10'; row.favoriteFood = 'Pancakes'; data.push(row); row = {...dataObject}; row.name = 'Jenny'; row.age = '11'; row.favoriteFood = 'Pie'; data.push(row); row = {...dataObject}; row.name = 'James'; row.age = '12'; row.favoriteFood = 'Fries'; data.push(row); // build table header let tableHeaderColumns = Object.keys(data[0]).map(colKey => `<th>${colKey}</th>`).join(''); const tableHeader = `<tr align=left>${tableHeaderColumns}</tr>`; // build table rows let i = 0; let tableRows = ''; let greyStyle = 'background-color: #EEE;'; data.forEach(function(rowObject) { const row = Object.values(rowObject).map(colValue => `<td>${colValue}</td>`).join(''); let rowStyle = ''; if(++i%2) { rowStyle = greyStyle; } tableRows += `<tr style='${rowStyle}'>${row}</tr>`; }); // build table (add desired styling) const table = `<table cellspacing=0 width=500 border=1 borderColor=#EEE style='border-collapse: collapse;'>${tableHeader}${tableRows}</table>`; // for demonstration display in div document.querySelector('div').innerHTML = table;
<div />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.