我使用查询创建了简单的库存控制表单。它包含(产品名称,价格) 单击添加按钮后,它将成功附加到表行上。我的问题是在添加价格一我的一最终后我无法计算最终的总数。我不知道该怎么做。到目前为止我尝试过的。我在下面写了它。任何人都可以浏览一下代码并给出一个好的解决方案吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add / Remove Table Rows</title>
<style type="text/css">
table{
width: 100%;
margin: 20px 0;
border-collapse: collapse;
}
table, th, td{
border: 1px solid #cdcdcd;
}
table th, table td{
padding: 5px;
text-align: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".add-row").click(function(){
tot = 0;
var ProductName = $("#ProductName").val();
var Price = $("#Price").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + ProductName + "</td><td>" + Price + "</td></tr>";
$("table tbody").append(markup);
tot += parseFloat(email);
});
// Find and remove selected table rows
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text" id="ProductName" placeholder="ProductName">
<input type="text" id="Price" placeholder="Price">
<input type="button" class="add-row" value="Add Row">
<label>Amount </label>
<input type="text" size="30" height="20" id="tot" placeholder="Total">
</form>
<table>
<thead>
<tr>
<th>Select</th>
<th>ProductName</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>
</body>
</html>
最佳答案
<body>
<form>
<input type="text" id="ProductName" placeholder="ProductName">
<input type="text" id="Price" placeholder="Price">
<input type="button" class="add-row" value="Add Row">
<label>Amount </label>
<input type="text" size="30" height="20" id="tot" placeholder="Total" readonly>
</form>
</body>
<script>
$(".add-row").click(function(){
var ProductName = $("#ProductName").val();
var Price = $("#Price").val();
var tot = $("#tot").val();
if(tot == ""){
tot = 0;
}
tot = parseFloat(tot) + parseFloat(Price);
$("#tot").val(tot);
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + ProductName + "</td><td>" + Price + "</td></tr>";
$("table tbody").append(markup);
});
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
var total = parseFloat($("#tot").val());
var newtotal = total - parseFloat($(this).data("price"));
$("#tot").val(newtotal);
$(this).parents("tr").remove();
}
});
});
</script>
关于javascript - 如何在JQuery中获取总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50949485/