[英]Calculating total price by iterating in the table using JavaScript
我正在做一个练习,我们必须使用HTML和JavaScript构建购物车。
在动态添加每行之后,并且在用户输入要购买的每种药物的数量之后,每行提供的数量将乘以指定的价格。 然后计算总数。
HTML代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Drug Shopping Cart</title>
<script type="text/javascript" src="drugShoppingCart.js"></script>
</head>
<body>
<h1 style="text-align:center">Drug shopping cart</h1>
<h2 style="text-align:center">Please enter your age & weight then choose what medicaments you want to buy to calculte the total price.</h2>
<div style="text-align:center">
<input type="text" value="Age" id="getAge" />
<input type="text" value="Weight" id="getWeight" />
</div>
<br />
<div style="border:groove; border-color:#006; background-color:rgb(0,51,153); color:rgb(255,255,255)">
<table cellspacing="50" id="shopTable" align="center">
<th>Drug Name</th>
<th>Price</th>
<th>Amount</th>
<th>Allergic</th>
<th>Amount of drug per item</th>
<th>Daily dose</th>
</table>
<br />
<input type="button" value="Add a new item" onClick="addTable()"> <button onclick="calculate()">Calculate</button>
<br />
</div>
</body>
</html>
脚本如下:
var prices = ['', 5, 10, 15, 20];
var amntOfDrg = ['',"500mg", "250mg", "1mg", "0.5mg"];
var i=0; //Global counter - counts the number of rows
var cell2;
var cell4;
var cell5;
var cell6;
var age=document.getElementById("getAge");
var weight=document.getElementById("getWeight");
var weight;
var dropDown;
function selectChange(selection) {
cell2.innerHTML = prices[selection.selectedIndex];
if(selection.selectedIndex == 2 || selection.selectedIndex==3)
cell4.innerHTML= "<input type='checkbox' name='Allergic' value='yes' checked onclick='return false'>";
else
cell4.innerHTML=" <input type='checkbox' name='Allergic' value='no' unchecked onclick='return false'>";
cell5.innerHTML= amntOfDrg[selection.selectedIndex];
}
function addTable(){
i++;
var table=document.getElementById("shopTable");
{
var row = table.insertRow(1);
var cell1= row.insertCell(0);
cell2= row.insertCell(1);
var cell3= row.insertCell(2);
cell4= row.insertCell(3);
cell5= row.insertCell(4);
cell6= row.insertCell(5);
cell1.innerHTML= "<select id=\"selectMenu\" " +
"onchange=\"selectChange(this)\">" +
"<option value=''>Select a drug:</option>" +
"<option value='1'>Paracetamol</option>" +
"<option value='2'>Ibuprofen</option>" +
"<option value='3'>Saxagliptin</option>"+
"<option value='4'>Liraglutide</option>"+
"</select>";
cell3.innerHTML= "<input type='text' id='amount' value='Enter the amount here' />";
}
}
function calculate(){
var table=document.getElementById('shopTable');
}
计算应在calculate()
函数中执行。
您是否知道如何通过访问所有金额输入来执行此计算?
function calculate(){
var table=document.getElementById('shopTable');
var count = table.getElementsByTagName('tr').length;
if (count > 0)
{
var total = 0;
for(var i = 1; i < count; i++)
{
total += table.rows[i].cells[1].innerHTML * table.rows[i].cells[2].children[0].value;
}
}
alert(total);
}
既然是练习,
你可以只给一个类你的细胞,那里的价格包含。 然后,您可以仅获取该类的所有单元格并在它们上循环
因此,包含价格的单元格将变成例如:
<td class="priceCell">19.90</td>
<td class="priceCell">29.90</td>
<td class="priceCell">9.90</td>
然后,您的脚本将变为:
var priceCells = document.getElementsByClassName("priceCell"); //returns a list with all the elements that have class 'priceCell'
var total=0;
//loop over the cells array and add to total price
for (var i = 0; i < priceCells.length; i++) {
var thisPrice = parseFloat(priceCells[i].innerHTML); //get inner text of this cell in number format
total = total + thisPrice;
};
total = total.toFixed(2); //give 2 decimal points to total - prices are, e.g 59.80 not 59.8
alert(total);
innerHTML
返回该单元格名称所暗示的innerText
还可以使用innerText
,但是并非所有浏览器都支持它,因此我改用了它。
像这样计算价格是完全错误的-有很多原因不应该在客户端以我建议的方式进行,但是我肯定不会在此答案中赘述
由内而外地锻炼。 首先,您需要能够记录一条记录并计算总数。 这意味着,获得一个表格行,获得数量和价格,并将它们相乘。
var record = document.getElementById('shopTable').rows[0];
var quantity = parseInt(record.cells[2].children[0].value, 10);
var price = parseFloat(record.cells[1].innerHTML);
var recordTotal = quantity*price;
下一步是将其实现为一个循环,该循环对数据结构中的每个记录执行相同的操作,然后将结果四舍五入到两位小数。
var records = document.getElementById('shopTable').rows, i, total = 0, quantity, price;
for (i = 0; i < records.length; i++) {
quantity = parseInt(records[i].cells[2].children[0].value, 10);
price = parseFloat(records[i].cells[1].innerHTML);
total += quantity * price;
}
total = total.toFixed(2);
可运行的示例:
var records = document.getElementById('shopTable').rows, i, total = 0, quantity, price; for (i = 0; i < records.length; i++) { quantity = parseInt(records[i].cells[2].children[0].value, 10); price = parseFloat(records[i].cells[1].innerHTML); total += quantity * price; } total = total.toFixed(2); document.getElementById('result').innerHTML = total;
#result { color: green; }
<table id="shopTable"> <tr> <td>name...</td> <td>2.56</td> <td><input type="text" value="1" readonly /></td> </tr> <tr> <td>name...</td> <td>6.52</td> <td><input type="text" value="3" readonly /></td> </tr> <tr> <td>name...</td> <td>5.26</td> <td><input type="text" value="0" readonly /></td> </tr> </table> <span id="result">n/a</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.