这是我的代码。
var products = ["Echo Dot", "Echo Plus", "Echo Auto", "Echo Show", "Echo Link"];
var prices = [49.99, 69.99, 129.99, 229.99, 1099.99];
toDisplay = "";
total = 0;
for (var i = 0; i < products.length; i++) {
toDisplay += "<li>" + products[i] + " - " + prices[i] + "</li>";
total += prices[i];
}
document.getElementById('prices').innerHTML = toDisplay;
<ol id="prices">
</ol>
最佳答案
使用 <table>
element . <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
这可能会带来一些问题。
关于javascript - 谁能告诉我如何使用 javascript/jquery 将其放入三列表中?产品、价格和折扣(计算 20%),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64616573/