最完美的购物车页面js,可全选,计算总价,传列表套字典。
<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 class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="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>
点击查看更多内容
30人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦