[英]Can anyone tell me how I could put this in three column table using javascript/jquery? Product, Price and Discount(calculating 20%)
Here is my code.这是我的代码。
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>
Use a<table>
element .使用
<table>
元素。 <table>
elements have a method called insertRow
which adds a new row to the table, and the row elements <tr>
have a method called insertCell
which adds a new cell to the row element. <table>
元素有一个名为insertRow
的方法,它向表格添加一个新行,而行元素<tr>
有一个名为insertCell
的方法,它向行元素添加一个新单元格。 We'll use both of those to add the data to the table instead of accumulating an html string, like so:我们将使用这两者将数据添加到表中,而不是累积一个 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>
I used textContent
to set the text of the newly added cell instead of innerHTML
that can some problems.我使用
textContent
来设置新添加的单元格的文本,而不是可能出现问题的innerHTML
。
Try this code :试试这个代码:
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.