简体   繁体   English

使用 inner.HTML 从给定数组创建表

[英]Create a table from a given array using inner.HTML

I'm asked to create a table which can be sorted with a press of a button.我被要求创建一个可以通过按下按钮进行排序的表格。 The table is supposed to be created by a given array.该表应该由给定的数组创建。

What I don't understand is how can I use an array loop inside a string so that the.innerHTML function would print the table body with the given object properties.我不明白的是如何在字符串中使用数组循环,以便.innerHTML function 将使用给定的 object 属性打印表格正文。

 main = document.getElementById('body'); listArray = [{name: 'Second', value: 2},{name: 'Fourth', value: 4},{name: 'First', value: 1},{name: 'Third', value: 3}]; let showAll = () => { main.innerHTML = ''; template(listArray); } let template = (arr) => { let loopArray = arr.forEach((item) => {return `<tr><td>${arr.name}</td><td>${arr.value}</td></tr>`}); let html = `<table> <thead><th>Name</th><th id="value">Value</thead> <tbody>` + loopArray + `</tbody></table>`; main.innerHTML += html; } showAll();

Use map instead of forEach so that the returned <tr> HTML string can then be joined together and set as the content of the table.使用map而不是forEach以便返回的<tr> HTML 字符串可以连接在一起并设置为表的内容。 You also need to refer to the properties of the item in the callback, not the arr .您还需要在回调中引用item的属性,而不是arr

 main = document.getElementById('body'); listArray = [{name: 'Second', value: 2},{name: 'Fourth', value: 4},{name: 'First', value: 1},{name: 'Third', value: 3}]; let showAll = () => { main.innerHTML = ''; template(listArray); } let template = (arr) => { const tableContentHTML = arr.map((item) => {return `<tr><td>${item.name}</td><td>${item.value}</td></tr>`}).join(''); let html = `<table> <thead><th>Name</th><th id="value">Value</thead> <tbody>` + tableContentHTML + `</tbody></table>`; main.innerHTML = html; } showAll();
 <div id="body"></div>

But concatenated HTML has security risks.但是串联的 HTML 存在安全风险。 If the input isn't known to be 100% trustworthy, a better approach would be to assign to the textContent of <td> s.如果不知道输入是 100% 可信的,更好的方法是分配给<td>textContent

 const main = document.getElementById('body'); const listArray = [{name: 'Second', value: 2},{name: 'Fourth', value: 4},{name: 'First', value: 1},{name: 'Third', value: 3}]; let showAll = () => { template(listArray); } let template = (arr) => { main.innerHTML = ''; const table = main.appendChild(document.createElement('table')); for (const item of arr) { const tr = table.appendChild(document.createElement('tr')); tr.appendChild(document.createElement('td')).textContent = item.name; tr.appendChild(document.createElement('td')).textContent = item.value; } }; showAll();
 <div id="body"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM