<html>
<head>
<meta charset="gb2312">
<title>购物车功能</title>
</head>
<body>
<!--这块是用的兄弟结点,节点元素不一样只改动span,看页面布局-->
<input class="check" type="checkbox" id="count_1" onclick="count(1)" product_id="101">产品一
单价<span id="price_1">10</span>
数量<span id="num_1">1</span>
<br>
<input class="check" type="checkbox" id="count_2" onclick="count(2)" product_id="102">产品二
单价<span id="price_2">20</span>
数量<span id="num_2">2</span>
<br>
<input class="check" type="checkbox" id="count_3" onclick="count(3)" product_id="103">产品三
单价<span id="price_3">30</span>
数量<span id="num_3">3</span>
<br>
<input class="check" type="checkbox" id="count_4" onclick="count(4)" product_id="104">产品四
单价<span id="price_4">40</span>
数量<span id="num_4">4</span>
<br>
<br><br><br><br>
合计:¥<span id="total">0</span>
<input type="checkbox" id="allcheck">全选<br><br>
<button onclick="pay()">结算</button>
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
</body>
<script>
// 全选/反选 功能
$('#allcheck').click(function(){
if(document.getElementById("allcheck").checked){
var oneCheck = $(".check");
for(var i=0;i<oneCheck.length;i++){
oneCheck[i].checked = true;
oneCheck.eq(i).attr("checked","checked");
}
setPrice();
}else{
var oneCheck = $(".check");
for(var i=0;i<oneCheck.length;i++){
oneCheck[i].checked = false;
oneCheck.eq(i).attr("checked",false);
}
// 反选总价清零
$('#total').html(0);
}
});
// 计算所有选中产品总价
function setPrice(){
var total = 0;
var checkTrue = $(".check");
for(var i=0;i<checkTrue.length;i++){
total = parseInt(total) + parseInt(checkTrue.eq(i).next("span").html() * checkTrue.eq(i).next("span").next("span").html())
}
$('#total').html(total);
}
// 单选计算总合计
function count(id){
var total = $('#total').html();
if(document.getElementById("count_"+id).checked){
$('#count_'+id).attr("checked","checked");
total = parseInt(total) + parseInt($('#price_'+id).html() * $('#num_'+id).html());
$('#total').html(total);
}else{
$('#count_'+id).attr("checked",false);
total = parseInt(total) - parseInt($('#price_'+id).html() * $('#num_'+id).html());
$('#total').html(total);
}
}
// 结算选中商品(列表套字典的形式传到后台)
function pay(){
var checkTrue = $(".check");
var buylist = new Array();
var product = "";
for (var i=0;i<checkTrue.length;i++){
if($(".check").eq(i).attr("checked") == "checked"){
product = '{"product_id":'+$(".check").eq(i).attr("product_id")+',"number":'+checkTrue.eq(i).next("span").next("span").html()+'}';
buylist.push(product);
}
}
if(buylist.length > 0){
buylist = '[' + buylist +']';
console.log(buylist);
}else{
alert("未选中商品");
}
}
</script>
</html>
打开App,阅读手记
热门评论
这是我2016年写的代码,写的确实欠很多火候,之后我会用vue封装一些实用的工具
计算总价怎么算不出来呀
这也拿出来呢。。。。我的天啊!!!!