javascript - Native js+localStorage to achieve shopping cart effect
高洛峰
高洛峰 2017-06-12 09:26:38
0
1
873

Question:
1. When the page is opened for the first time, since there is no local storage, the data will not be retrieved. The product will be added by 1 and will not be added to the shopping cart. However, 1 will be added and 2 items will be added to the shopping cart at once. Lesson normal addition and subtraction
2. When adding the first item of each product, it will not be added to the shopping cart when the second item is added.

Display effect: https://ityanxi.github.io/seg...
Code address: https://github.com/ityanxi/se...

js code:

//获取元素
function $(id){
    return document.getElementById(id);
}
var table =$('cartTable'); // 购物车表格
var tr = table.children[1].rows; //行
var priceTotal = $('priceTotal'); //总计
var selectedTotal =$('selectedTotal'); //已选商品数目容器
var selectedViewList =  $('selectedViewList'); //浮层已选商品列表容器
var foot =  $('foot');
    
     
    
utils = {
    setParam : function (name,value){  //存储数据
        localStorage.setItem(name,value)  
    },  
    getParam : function(name){  //获取数据
        return localStorage.getItem(name)  
    }  
}  

product={  
    name:"",  
    num:0,  
    price:0.00,  
};  

orderdetail={  
    username:"",  
    phone:"",  
    address:"",  
    zipcode:"",  
    totalNumber:0,  
    totalAmount:0.00      
}  

cart = {  
    //向购物车中添加商品  
    addproduct: function (product) {  
        var ShoppingCart = utils.getParam("ShoppingCart");  //获取数据
            
        if (ShoppingCart == null || ShoppingCart == "") {  
            //第一次加入商品  
            var jsonstr = { "productlist": [{ 
                                            "name": product.name, //商品名称
                                            "num": product.num, //商品数量
                                            "price": product.price}], //商品单价
                            "totalNumber": product.num, //单一商品总数
                            "totalAmount": (product.price * product.num) //商品总价
            };
            
            
            //JSON.stringify(jsonstr)   //将json对象转换成字符串.
            utils.setParam("ShoppingCart", "'" + JSON.stringify(jsonstr));  //存储数据
           
             
        } else {  
            //JSON.parse(ShoppingCart.substr(1, ShoppingCart.length))//对json数据的解释    将字符串变成json对象
            var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));  
            var productlist = jsonstr.productlist;  
            var result = false;  
            //查找购物车中是否有该商品  
            for (var i in productlist) {  
                if (productlist[i].name == product.name) {  
                    productlist[i].num = parseInt(productlist[i].num) + parseInt(product.num);  
                    result = true;  
                }  
            }  
            if (!result) {  
                //没有该商品就直接加进去  
                productlist.push({"name": product.name, "num": product.num, "price": product.price });  
            }  
            //重新计算总价  
            jsonstr.totalNumber = parseInt(jsonstr.totalNumber) + parseInt(product.num);  
            jsonstr.totalAmount = parseFloat(jsonstr.totalAmount) + (parseInt(product.num) * parseFloat(product.price));  
           
            //保存购物车  
            utils.setParam("ShoppingCart", "'" + JSON.stringify(jsonstr));  
          
        }  
       
       
       
    },  
    //修改给买商品数量  
    updateproductnum: function (name, num) {  
        console.log(name,'+++:',num);
        var ShoppingCart = utils.getParam("ShoppingCart");  
        var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));  
        console.log(jsonstr);
        var productlist = jsonstr.productlist;  
  
        for (var i in productlist) {  
            if (productlist[i].name == name) {  
                jsonstr.totalNumber = parseInt(jsonstr.totalNumber) + (parseInt(num) - parseInt(productlist[i].num));  
                console.log(parseInt(jsonstr.totalNumber),parseInt(productlist[i].num));
                jsonstr.totalAmount = parseFloat(jsonstr.totalAmount) + ((parseInt(num) * parseFloat(productlist[i].price)) - parseInt(productlist[i].num) * parseFloat(productlist[i].price));
                productlist[i].num = parseInt(num);  
                orderdetail.totalNumber = jsonstr.totalNumber;  
                orderdetail.totalAmount = jsonstr.totalAmount;  
                
                selectedTotal.innerHTML= orderdetail.totalNumber;
                priceTotal.innerHTML=(orderdetail.totalAmount).toFixed(2);//保留两位小数
                
                utils.setParam("ShoppingCart", "'" + JSON.stringify(jsonstr)); 
                
                console.log("'"+ JSON.stringify(jsonstr))
                return;  
            }  
        }  
        
    },  
    //获取购物车中的所有商品  
    getproductlist: function () {  
        var ShoppingCart = utils.getParam("ShoppingCart");  
        var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));  
        var productlist = jsonstr.productlist;  
        orderdetail.totalNumber = jsonstr.totalNumber;  
        orderdetail.totalAmount = jsonstr.totalAmount;  
        return productlist;  
    },  
    //判断购物车中是否存在商品  
    existproduct: function (name) {  
        var result = false;  
        var ShoppingCart = utils.getParam("ShoppingCart");  
        if (ShoppingCart != null) {  
            var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));  
            var productlist = jsonstr.productlist;  
            for (var i in productlist) {  
                if (productlist[i].name == name) {  
                    result = true;  
                }  
            }  
        }  
        return result;  
    },  
    //删除购物车中商品  
    deleteproduct: function (name) {  
        var ShoppingCart = utils.getParam("ShoppingCart");  
        var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));  
        var productlist = jsonstr.productlist;  
        var list = [];  
        for (var i in productlist) {  
            if (productlist[i].name == name) {  
                jsonstr.totalNumber = parseInt(jsonstr.totalNumber) - parseInt(productlist[i].num);  
                jsonstr.totalAmount = parseFloat(jsonstr.totalAmount) - parseInt(productlist[i].num) * parseFloat(productlist[i].price);  
            } else {  
                list.push(productlist[i]);  
            }  
        }  
        jsonstr.productlist = list;  
        orderdetail.totalNumber = jsonstr.totalNumber;  
        orderdetail.totalAmount = jsonstr.totalAmount;  
        utils.setParam("ShoppingCart", "'" + JSON.stringify(jsonstr));  
    }  
};  
    loadData()
    //加载数据
    function loadData(){
        if(localStorage.length>0){//如果有存储数据 则获取并渲染
            var productlist=cart.getproductlist();//取出购物车商品  
            var countInput = table.getElementsByClassName('count-input'); //数目input
            var goods=table.getElementsByClassName('goods');
            var names=[];
            for(var i=0;i<goods.length;i++){
                //console.log(goods[i].children[1].innerHTML);
                names.push(goods[i].children[1].innerHTML);
            }
            
            //var names=goods.children[1];
               //console.log(productlist);
             //console.log(names);
            
            for(var i=0;i<names.length;i++){
                for(var j=0;j<productlist.length;j++){
                    if(names[i]==productlist[j].name){
                        //console.log(i)
                        countInput[i].value=productlist[j].num
                    }
                    
                }
            }
            
               for(var i=0;i<productlist.length;i++){
                   console.log(productlist[i]);
                   
                   var str='    名称:'+productlist[i].name+'        数量:'+productlist[i].num+'        小计:'+(parseInt(product.num) * parseFloat(product.price))
                   console.log(str);
               }
            
            selectedTotal.innerHTML= orderdetail.totalNumber;
             priceTotal.innerHTML=(orderdetail.totalAmount).toFixed(2);//保留两位小数
        }else{
            return
        }
    }
    
  
    
    //为每行元素添加事件
    for (var i = 0; i < tr.length; i++) {
        //将点击事件绑定到tr元素
        tr[i].onclick = function (e) {
            var e = e || window.event;
            var el = e.target || e.srcElement; //通过事件对象的target属性获取触发元素
            var cls = el.className; //触发元素的class
            var countInout = this.getElementsByTagName('input')[0]; // 数目input
            var value = parseInt(countInout.value); //数目
            var goods=this.getElementsByClassName('goods')[0];
            var name=goods.children[1].innerHTML;
           
           
            var price=this.getElementsByClassName('price')[0].innerHTML;
            //通过判断触发元素的class确定用户点击了哪个元素
            switch (cls) {
                case 'add': //点击了加号
                    countInout.value = value + 1;
                    break;
                case 'reduce': //点击了减号
                    if (value > 0) {
                       countInout.value = value - 1;
                    }
                    break;
            }
            
           
            var product =  
                {  
                         //属性名用引号括起来,属性间由逗号隔开  
                    'name': name,  
                    'num':countInout.value,  
                    'price':price  
                };  
            console.log(product.num);
            
            if(cart.existproduct(product.name)){
                cart.updateproductnum(product.name,product.num);
            }else{
                
                cart.addproduct(product)
            }
            
           //loadData()
        }
    }
    
    


function remove1(){
        localStorage.removeItem("ShoppingCart")//删除变量名为key的存储变量 
    }
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!