2 回答
TA贡献1719条经验 获得超6个赞
使用一个<table>
元素。<table>
元素有一个名为 的方法insertRow
,该方法将新行添加到表中,并且行元素<tr>
有一个名为 的方法insertCell
,该方法将新单元格添加到行元素。我们将使用这两个方法将数据添加到表中,而不是累积 html 字符串,如下所示:
var products = ["Echo Dot", "Echo Plus", "Echo Auto", "Echo Show", "Echo Link"];
var prices = [49.99, 69.99, 129.99, 229.99, 1099.99];
var discountPercent = 20;
var table = document.getElementById("the-table");
for (var i = 0; i < products.length; i++) {
var row = table.insertRow();
row.insertCell().textContent = products[i];
row.insertCell().textContent = prices[i];
row.insertCell().textContent = ((100 - discountPercent) * prices[i] / 100).toFixed(2);
}
table {
border-collapse: collapse;
}
table td, table th {
border: 1px solid black;
padding: 5px 10px;
}
<table id="the-table">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Price After 20% Discount</th>
</tr>
</thead>
</table>
我曾经textContent
设置新添加的单元格的文本,而不是设置innerHTML
可能会出现一些问题。
TA贡献1942条经验 获得超3个赞
试试这个代码:
<body>
<table id="prices"></table>
<script>
var title = ["Product", "Price", "Discount"];
var products = [
"Echo Dot",
"Echo Plus",
"Echo Auto",
"Echo Show",
"Echo Link",
];
var prices = [49.99, 69.99, 129.99, 229.99, 1099.99];
var discount = prices.map(myFunction);
function myFunction(value) {
return ((value * 80) / 100).toFixed(2);
}
var toDisplay = "";
var t = "";
var i = 0;
for (; i < products.length; i++) {
if (i < title.length) {
t += "<th>" + title[i] + "</th>";
}
toDisplay +=
"<tr>" +
"<td>" +
products[i] +
"</td>" +
"<td>" +
prices[i] +
"</td>" +
"<td>" +
discount[i] +
"</td>" +
"</tr>";
}
t = "<tr>" + t + "</tr>" + toDisplay;
document.getElementById("prices").innerHTML = t;
</script>
</body>
添加回答
举报