需求
购物网站中常见的购物车中实时统计费用的功能,可以用前端JS来实现,下面来看这个例子
效果
JS主要通过JQuery的选择器,来动态监听各个元素的状态值并作计算
$(function(){
$(".btn").click(function(){
if(this.value=="+"){
var $v=$(this).prev();
var s=parseInt($v.val());
$v.val(s+1);
}else{
var $v=$(this).next();
var s=parseInt($v.val());
if(s==0){
$v.val(0);
}else{
$v.val(s-1);
}
}
var $tr=$(this).parents("tr");
var price = parseFloat($tr.find("td:eq(1)").text());
var num=parseInt($tr.find("td:eq(2) input:eq(1)").val());
var sum=num*price;
$tr.find("td:last").text(sum.toFixed(2));
var $table=$(this).parents("table");
var $tds=
$table.find("tr:not('tr:first'):not('tr:last')").find("td:last");
var total=0;
for(var i=0;i<$tds.length;i++){
total+=parseFloat($($tds[i]).text());
}
$table.find("td:last").text(total.toFixed(2));
})
})
CSS
@charset "utf-8";
.num{
width: 30px;
}
table{
text-align: center;
}
#total{
text-align: right;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="jq练习.css"/>
<script src="jquery-1.9.1.min.js" type="text/javascript"
charset="utf-8"></script>
<script src="jq练习.js" type="text/javascript"
charset="utf-8"></script>
</head>
<body>
<table border="1px" cellspacing="0px"
cellpadding="0px">
<tr>
<td style="width: 100px;">商品名称</td>
<td style="width: 100px;">价格</td>
<td style="width: 100px;">数量</td>
<td style="width: 100px;">小计</td>
</tr>
<tr>
<td>兰花</td>
<td>10.00</td>
<td>
<input class="btn" type="button" value="-" />
<input class="num" type="text" value="1" />
<input class="btn" type="button" value="+" />
</td>
<td>10.00</td>
</tr>
<tr>
<td>玫瑰</td>
<td>5.00</td>
<td>
<input class="btn" type="button" value="-" />
<input class="num" type="text" value="1" />
<input class="btn" type="button" value="+" />
</td>
<td>5.00</td>
</tr>
<tr>
<td>康乃馨</td>
<td>15.00</td>
<td>
<input class="btn" type="button" value="-" />
<input class="num" type="text" value="1" />
<input class="btn" type="button" value="+" />
</td>
<td>15.00</td>
</tr>
<tr>
<td colspan="3" id="total">总计:</td>
<td>30.00</td>
</tr>
</table>
</body>
</html>