我习惯于通过 php 执行此操作,但现在转向 js(新手),我不明白为什么它不起作用!
还请除 document.write 以外的任何建议?因为我不想删除我以后制作的html。
我想要的只是将 js 数组值发布到 html 表中。
当我写:document.getElementById("demo").innerHTML += '<table><tr><td>'+item +'</td></tr></table>';
它有效,但每次都创建表格,这是错误的
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<span id="demo"></span>
<script>
document.write("<table>");
arrayjs.forEach(myFunction);
document.write("</table>");
function myFunction(item) {
document.getElementById("demo").innerHTML += '<tr><td>'+item +'</td></tr>';
}
</script>
</body>
</html>
最佳答案
您应该避免 document.write
的想法是正确的,因为它通常被认为是不好的做法,应该尽可能避免。更好的方法是使用原生方法创建元素并将它们添加到 DOM,例如 createElement()
和 appendChild()
。
您可以使用这种方法在其中创建一个table
和一个tbody
。从那里 tbody
有一些方法可以让你创建行,并从那里创建行中的单元格。
下面是如何执行此操作的示例。
let arrayjs = ['foo', 'bar', 'fizz', 'buzz'];
let container = document.querySelector('#demo');
tableFromArray(arrayjs, container);
function tableFromArray(arr, container) {
let table = document.createElement('table');
let tbody = document.createElement('tbody');
container.appendChild(table);
table.appendChild(tbody)
arr.forEach(item => {
let tr = tbody.insertRow(tbody.rows.length); // add a new row
let td = tr.insertCell(tr.cells.length); // add a new cell within the row
td.textContent = item;
});
}
table,
td {
border: 1px solid black;
}
<span id="demo"></span>
关于javascript - 在 html 表中发布 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65681406/