jQuery实现淘宝购物车核心功能详解
本次开发需满足以下具体业务需求:
第一,在购物车界面中,若勾选“全选”选项,则所有商品对应的复选框应自动处于选中状态;反之,若取消全选,则所有商品复选框均被取消选中。
第二,当页面上所有商品的复选框全部被选中时,“全选”复选框应自动变为选中状态;只要有一个商品未选中,全选框即取消选中。
第三,点击数量减少图标时,商品数量减一,但数量不能低于零,同时需重新计算商品总价与累计积分。
第四,点击数量增加图标时,商品数量加一,同样需要实时更新商品总价与累计积分。
第五,点击“删除所选”按钮可移除用户已勾选的商品,点击单个商品的删除按钮则仅移除该商品,两者均需触发总价与积分的重新计算。
接下来展示具体的代码实现部分:
$(function () {
subtotal();
addorminus();
allcheckbox();
delet();
deleselect();
});
//设置 获取积分和一共金额函数
function countmoney() {
var money = 0; //总金额
var jifen = 0; //总积分
$(".cart_td_7").each(function () {
var m = $(this).text();
money += Number(m);
var j = $(this).siblings(".cart_td_4").text();
var number = $(this).siblings(".cart_td_6").children("input").val();
jifen += Number(j * number);
});
$("#total").html(money);
$("#integral").html(jifen);
}
//小计
function subtotal() {
var obj = $(".cart_td_7");
obj.each(function () { //each遍历每一个clss为.card_td_7的元素
var num = $(this).siblings(".cart_td_6").children("input").val(); //购物车 选中的当前数量
var price = $(this).siblings(".cart_td_5").html(); //当前选中物品的price
var money = num * price; //小计
$(this).html(money);
});
countmoney();
}
//添加或减少数量
function addorminus() {
$(".hand").on("click", function () {
var num;
if ($(this).attr("alt") == "minus") {
num = $(this).next().val();
if (num == 1) {
$(this).css("display", "none");
} else {
$(this).next().val(--num);
}
} else {
num = $(this).prev().val();
$(this).prev().val(++num);
if (num == 1) {
$(this).siblings("[alt==minus]").css("display", "visible");
} else { }
}
subtotal();
});
}
//全选或者全不选
function allcheckbox() {
$("#allCheckBox").live("change", function () {
if ($(this).attr("checked") == "checked") {
$("[name=cartCheckBox]").attr("checked", "checked");
} else {
$("[name=cartCheckBox]").attr("checked", false);
}
});
$("[name=cartCheckBox]").live("change", function () {
var bool = true;
$("[name=cartCheckBox]").each(function () {
if ($(this).attr("cheked") != "checked") {
bool = false;
}
});
if (bool) {
$("#allCheckBox").attr("checked", "checked");
} else {
$("#allCheckBox").attr("checked", false);
}
});
}
//删除
function delet() {
$(".cart_td_8>a").live("click", function () {
$(this).parent().parent().prev().remove();
$(this).parent().parent().remove();
subtotal();
});
}
//删除所选
function deleselect() {
$("#deleteAll>img").live("click", function () {
$("[name=cartCheckBox]").each(function () {
if ($(this).attr("checked") == "checked") {
$(this). parent().parent().prev().remove();
$(this).parent().parent().remove();
}
});
subtotal();
});
}
以上即为完整的功能实现内容,希望这些代码能协助大家更好地掌握相关技术,欢迎继续支持本站获取更多资源!