2 回答

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個贊
使用一個<table>
元素。<table>
元素有一個名為 的方法insertRow
,該方法將新行添加到表中,并且行元素<tr>
有一個名為 的方法insertCell
,該方法將新單元格添加到行元素。我們將使用這兩個方法將數(shù)據(jù)添加到表中,而不是累積 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>
我曾經(jīng)textContent
設(shè)置新添加的單元格的文本,而不是設(shè)置innerHTML
可能會出現(xiàn)一些問題。

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超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>
添加回答
舉報(bào)