淘宝购物车 原生js写法




    
    
    


全选 商品信息 单价 数量 金额 操作
豫竹香辣牛肉方便面60包 袋装速食干吃面干脆面泡面整箱包邮特价 ¥39.00 ¥39.00 删除
豫竹香辣牛肉方便面60包 袋装速食干吃面干脆面泡面整箱包邮特价 ¥39.00 ¥39.00 删除
豫竹香辣牛肉方便面60包 袋装速食干吃面干脆面泡面整箱包邮特价 ¥39.00 ¥39.00 删除
豫竹香辣牛肉方便面60包 袋装速食干吃面干脆面泡面整箱包邮特价 ¥39.00 ¥39.00 删除
豫竹香辣牛肉方便面60包 袋装速食干吃面干脆面泡面整箱包邮特价 ¥39.00 ¥39.00 删除
全选 已选商品0 合计:0
var btnck = document.getElementsByClassName("ckbox");
var ckall = document.getElementsByClassName("ckbtn");
var count=0;
for (var i = 0; i < ckall.length; i++) {
    ckall[i].onclick = function () {
       if(this.checked){
           count++;;
       }
        else{
           count--;
       }
        if(count==ckall.length)
        {
            btnck[0].checked=true;
            btnck[1].checked=true;
        }
        else{
            btnck[0].checked=false;
            btnck[1].checked=false;
        }
        addtotle();
    }
}
for (var index in btnck) {
    btnck[index].index = index;
    btnck[index].onclick = function () {
        btnck[this.index == 0 ? 1 : 0].checked = !btnck[this.index == 0 ? 1 : 0].checked;
        if(this.checked)
        {
            for (var i = 0; i < ckall.length; i++) {
                ckall[i].checked = true;
            }
        }
        else{
            for (var i = 0; i < ckall.length; i++) {
                ckall[i].checked = false;
            }
            count=0;
        }
        addtotle();
    }
}

var btnleft = document.getElementsByClassName("btnleft");
var btnright = document.getElementsByClassName("btnright");
var txt = document.getElementsByClassName("txt");
var price = document.getElementsByClassName("price");
var totle = document.getElementsByClassName("totle");
var tprice = document.getElementsByClassName("totleprice");
var num=document.getElementsByClassName("number");
for (var i = 0; i < btnleft.length; i++) {
    btnleft[i].index = i;
    btnleft[i].onclick = function () {
        var val = txt[this.index].value;
        val--;
        if (val < 1) {
            val = 1;
        }
        txt[this.index].value = val;
        addprice(this.index, val);
        addtotle();
    }
    btnright[i].index = i;
    btnright[i].onclick = function () {
        var val = txt[this.index].value;
        val++;
        txt[this.index].value = val;
        addprice(this.index, val);
        addtotle();
    }
}

function addprice(index, value) {
    totle[index].innerHTML = "共" + (price[index].getAttribute("data-price") * value).toFixed(2);
    totle[index].setAttribute("data-totle", (price[index].getAttribute("data-price") * value).toFixed(2));
}

function addtotle() {
    var totleprice = 0;
    var number=0;
    for (var i = 0; i < ckall.length; i++) {
        if (ckall[i].checked) {
            totleprice += parseFloat(totle[i].getAttribute("data-totle"));
            number+=parseInt(txt[i].value);
        }
    }
    tprice[0].innerHTML = "共" + totleprice.toFixed(2);
    num[0].innerHTML=number;
}

考虑到代码的优化,还是建议使用jQuery框架来写,原生js代码个人感觉很冗杂。

你可能感兴趣的:(淘宝购物车 原生js写法)