淘宝京东购物车价格计算,商品店铺联动js

来源:互联网 发布:威宁谢成本数据库 编辑:程序博客网 时间:2024/04/26 06:09
{% extends 'mobile/include/common_page_template.html' %}{% load xiaozhuang_console_tag %}{% block title %}    购物车{% endblock %}{% block body %}    <div class="works-head" style="background: #fbbc50">        <a class="iconBack icon iconfont_list" href="javascript: history.go(-1);">&#xe693;</a>        <h1 style="font-size: 16px;font-weight: normal;">购物车</h1>        <p class="car_product_modify" id="modify">编辑</p>    </div>    <div class="product_car_contaier">        {% for provider in provider_list %}            <div class="product_parent">                <div class="product_car_headInfo">                    <p class="productCar_info"><span><i                            class="iconfont_car car_select car_store">&#xe62e;</i></span><span><i                            class="iconfont_car">&#xe607;</i></span><span>{{ provider.provider_user.name }}</span><span> > </span>                    </p>                </div>                {% for cart_item in provider.cart_item_list %}                    <div class="car_product_detail">                        <p class="flex-center"><span><i class="iconfont_car car_select deleteTag">&#xe62e;</i></span>                        </p>                        <p class="car_product_img"><img src="/static/mobile/images/psds40528.jpg" alt=""></p>                        <div class="car_product_description">                            <p> {{ cart_item.product.name }}</p>                            <p class='car_product_main'>主材套餐</p>                            <p class="product_car_meal">月销12 笔 </p>                            <p class="car_product_detail_price">{{ cart_item.product.price }}</p>                            {#                store init value#}                            <input type="hidden" value={{ cart_item.product.price }} class="product_car_initValue">                            <input type="hidden" value={{ cart_item.product.id }} class="product_id_initValue">                            <div class="gw_num">                                <em class="jian">-</em>                                <input type="text" value="1" class="num"/>                                <em class="add">+</em>                            </div>                        </div>                    </div>                {% endfor %}            </div>        {% endfor %}        {#------------footer------------#}        <ul class="car_product_pay flex">            <li><i class="iconfont_car " id="all_select">&#xe62e;</i></li>            <li>                <span>全选</span>                <div class="product_car_price" id="product_price_show">                    <p class="car_product_payInfo" id="product_totalPrice">合计:¥ <span>22000</span></p>                    <p style="height: 20px;">不含运费</p>                </div>            </li>            <li><span id="car_calculate">                <a href="{% url 'mobile_customer_corder_create' %}">                    结算                </a>            </span><span id="total_num">(0)</span></li>        </ul>        <div style="height: 80px;"></div>        {#--------------------------ProductCar.js-------------------------------#}        <script type="text/javascript">            //核心理念 :!important 点击更换样式,改变自定义属性的值(价格通过自定义属性计算)            /**             * init js             * author ly             * @type {*|jQuery|HTMLElement}             */            var mTotal_money = 0;            updatePrice(mTotal_money);            //all select            var all_select = $('#all_select');            $(document).ready(function () {                CarJsInit();            });            /**             * init value             * first step  : calculate the total money  foreach price             * author ly             * @type {*|jQuery|HTMLElement}             */            function CarJsInit() {                all_select.attr('select', 'one');                selectAll();            }            /**             * all_select button event             * author ly             * @type {*|jQuery|HTMLElement}             */            function selectAll() {                if (all_select.attr('select') == 'one') {                    all_select.html('&#xe658;').css('color', '#f24f00');                    $('.car_select').html('&#xe658;').css('color', '#f24f00');                    all_select.attr('select', 'two');                    $('.car_select').attr('clickNum', 'two');                    calculate();                } else if (all_select.attr('select') == 'two') {                    updatePrice(0);                    $('#total_num').html("(" + 0 + ")");                    all_select.attr('select', 'one');                    all_select.html('&#xe62e;').css('color', '#9f9f9d');                    $('.car_select').html('&#xe62e;').css('color', '#9f9f9d');                    $('.car_select').attr('clickNum', 'one');                }            }            $('#all_select').click(function () {                selectAll();            });            /**             * Click change event             * author ly             * @type {*|jQuery|HTMLElement}             */            var select = $('.car_select');            select.attr('clickNum', 'one');            var num = 0;            select.click(function () {                var num = $(this).attr('clickNum');                if (num == 'one') {                    var select_num = 0;                    $(this).attr('clickNum', 'two');                    calculate();                    $(this).html('&#xe658;').css('color', '#f24f00');                } else {                    $(this).attr('clickNum', 'one');                    calculate();                    $(this).html('&#xe62e;').css('color', '#9f9f9d');                }                var shop_select = $(this).parents('.car_product_detail').siblings('.product_car_headInfo').find('.car_select');                //  var brother = $(this).parents('.car_product_detail').siblings('.car_product_detail');                var brother = $(this).parents('.product_parent').find('.car_product_detail');                for (var i = 0; i < brother.length; i++) {                    if (brother.eq(i).find('.car_select').attr('clicknum') == 'one') {                        //return 表示这个方法结束                        //有一个未选中就表示,上边选中状态为未选中状态                        shop_select.html('&#xe62e;').css('color', '#9f9f9d');                        shop_select.attr('clicknum', 'one');                        select_num++;                        break;                    }                }                if (select_num == 0) {                    shop_select.html('&#xe658;').css('color', '#f24f00');                    shop_select.attr('clicknum', 'two');                }            });            /**             * deal with delete click             * author ly             * @type {*|jQuery|HTMLElement}             */            $('#car_calculate').click(function () {                var product = $('.car_product_detail');                var price = $('.car_product_detail_price');                var calHtml = $('#car_calculate').html()                if (calHtml == '删除') {                    //TODO: delete the element that you select                    var car_select = $('.deleteTag');                    for (var i = 0; i < car_select.length; i++) {                        var count = 0;                        if (car_select.eq(i).attr('clickNum') == 'two') {                            car_select.eq(i).attr('statu', '001');                            car_select.eq(i).attr('clickNum', 'one');                            //todo: reduce money                            mTotal_money -= parseInt(price.eq(i).html());                            //update the money                            updatePrice(mTotal_money);                            var num = product.eq(i).siblings();                            for (var j = 0; j < num.length; j++) {                                if (num.eq(j).css('display') != 'none') {                                    count++;                                }                            }                            product.eq(i).hide();                            if (count == 1) {                                product.eq(i).parent().hide();                            }                        }                    }                } else if (calHtml == '结算') {                    if (!isNull()) {                        //todo : deal with calculate method                        // save product_info into Car                        saveProductInfo();                        window.location.href = "{% url 'mobile_customer_corder_create' %}";                    } else {                        alert('购物车无需要结算商品');                    }                }            });            /**             * modify click             * author ly             * @type {*|jQuery|HTMLElement}             */            $('#modify').click(function () {                var modify = $('#modify').html();                if (modify == '完成') {                    $('#total_num').show();                    $('#modify').html('编辑');                    $('#car_calculate').html('结算');                    $('#product_price_show').css('display', 'block');                    $('.car_select').attr('clickNum', 'one');                    $('#total_num').html("(" + 0 + ")");                } else if (modify == '编辑') {                    $('#total_num').hide();                    $('#modify').html('完成');                    $('#car_calculate').html('删除');                    $('#product_price_show').css('display', 'none');                    $('.car_select').attr('clickNum', 'one');                    updatePrice(0);                    $('#total_num').html("(" + 0 + ")");                }                $('.car_select').html('&#xe62e;').css('color', '#9f9f9d');                //todo :                $('#all_select').html('&#xe62e;').css('color', '#9f9f9d');            });            $(document).ready(function () {                //add Product                $(".add").click(function () {                    var n = $(this).prev().val();                    var num = parseInt(n) + 1;                    if (num == 0) {                        return;                    }                    $(this).prev().val(num);                    //TODO:  calculate Money                    //todo :  important  get the value when not in same father                    var index = $('.add').index(this);                    calculate();                });                //reduce Product                $(".jian").click(function () {                    var n = $(this).next().val();                    var num = parseInt(n) - 1;                    if (num == 0) {                        return                    }                    $(this).next().val(num);                    var index = $('.jian').index(this);                    calculate();                });            })            /**             * despriction: calculate the money and update total price             * author ly             * @type {*|jQuery|HTMLElement}             */            function calculate() {                mTotal_money = 0;//init                var total_num = 0;                var car_product_num = 0;// the num of product                //todo : the calculate is wrong you can remember init value or add or -                //TODO : CALCULATE MONEY NEED INIT VALUE!;                var curr_money = $('.car_product_detail_price');                var product_num = $('.num');                for (var i = 0; i < curr_money.length; i++) {                    var product_selecte = $('.car_product_detail_price').eq(i).parent().prev().prev().children(0).children(0);                    if (product_selecte.attr('clickNum') == 'two' && product_selecte.attr('statu') != '001') {                        var price = parseInt(product_num.eq(i).val()) * parseInt($('.product_car_initValue').eq(i).val());                        mTotal_money += price;                        updatePrice(mTotal_money);                        car_product_num++;                        total_num += parseInt(product_num.eq(i).val());                    }                    //表示没有一个是选中的,直接设置位0就好了                    // 循环到最后 还是会走 0                    if (car_product_num == 0) {                        updatePrice(0);                        $('#total_num').html("(" + 0 + ")");                    }                }                $('#total_num').html("(" + total_num + ")");            }            /**             * despriction: Shop and commodity linkage             * ① 当选中上方标题时遍历  下边 商品节点 状态改为 选中状态             ② 当全选中下方时,更改标题为选中状态             ③ 当下方有一未选中时,更改更改标题为未选中状态             ④ ---------> 变为选中状态 添加 class 之前 要先更改   自定义属性             * author ly             * @type {*|jQuery|HTMLElement}             */            $(document).ready(function () {                $('.car_store').click(function () {                    //这是点击之后 执行的  原本是 two 点击之后变成 One                    var num = $(this).attr('clicknum');                    if (num == 'one') {                        $(this).parents('.product_car_headInfo').siblings().find('.car_select').html('&#xe62e;').css('color', '#9f9f9d');                        $(this).parents('.product_car_headInfo').siblings().find('.car_select').attr('clicknum', 'one');                    } else {                        $(this).parents('.product_car_headInfo').siblings().find('.car_select').html('&#xe658;').css('color', '#f24f00');                        $(this).parents('.product_car_headInfo').siblings().find('.car_select').attr('clicknum', 'two');                    }                    calculate();                });            });            // update Price function            function updatePrice(price) {                if (price >= 0)                    $('#product_totalPrice').html('合计' + price);                else                    $('#product_totalPrice').html('合计' + price);            }            /**             * despriction: cookie init and Exposed interface             * author ly             * @type {*|jQuery|HTMLElement}             */            //TODO: 点击去结算的时候 当购物车为空的时候 告诉用户 购物车是空的            var cookieJson = [];            function saveProductInfo() {                //  total price  price num  id                var car_select = $('.deleteTag');                var cookieJsonStr = '';                for (var i = 0; i < car_select.length; i++) {                    if (car_select.eq(i).attr('clickNum') == 'two') {                        // var currPrice = $('.car_product_detail_price').eq(i).html();                        var num = $('.num').eq(i).val();                        var proId = $('.product_id_initValue').eq(i).val();                        if (i != car_select.length - 1) {                            cookieJsonStr += '[' + proId + ',' + num + ',' + 1 + '],';                        } else {                            cookieJsonStr += '[' + proId + ',' + num + ',' + 1 + ']';                        }                    }                }                var cookieJson = '[' + cookieJsonStr + ']';                setCookie('cart_info', cookieJson, "d30");                var xiaozhuangCart = new XiaozhuangCart();//--------------------------------------------------------------------------------------------------------------------------------                // ajax get to get total price                $.get("http://127.0.0.1:8000/mobile/mall/cart/price", function (data, status) {                    alert("Data: " + data.total_price + "\nStatus: " + status);                    // update price                    //updatePrice(data.total_price);                });                //     setCookie('cart_info', window.JSON.stringify(cookieJson), "d30");            }            /**             * despriction: Judge whether the shopping cart is empty             * author ly             * @type {*|jQuery|HTMLElement}             */            function isNull() {                var car_product_num = 0;                var curr_money = $('.car_product_detail_price');                var product_num = $('.num');                for (var i = 0; i < curr_money.length; i++) {                    var product_selecte = $('.car_product_detail_price').eq(i).parent().prev().prev().children(0).children(0);                    if (product_selecte.attr('clickNum') == 'two' && product_selecte.attr('statu') != '001') {                        car_product_num++;                    }                    if (car_product_num == 0) {                        return 1;                    }                    return 0;                }            }            //cookie 测试函数,使用cookie 存储json 数据,获取json 数据的值            $(function () {                saveProductInfo();                var cookieJson = getCookie("car_Info");                var cooieJsonVar = JSON.parse(cookieJson);            });            //cookie 封装 获取 cookie            function getCookie(name) {                var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");                if (arr = document.cookie.match(reg))                    return unescape(arr[2]);                else                    return null;            }            //删除cookie            function delCookie(name) {                var exp = new Date();                exp.setTime(exp.getTime() - 1);                var cval = getCookie(name);                if (cval != null)                    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();            }            //设置cookie 以及过期时间            function setCookie(name, value, time) {                var strsec = getsec(time);                var exp = new Date();                exp.setTime(exp.getTime() + strsec * 1);                document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();            }            //获取设置过期时间            function getsec(str) {                var str1 = str.substring(1, str.length) * 1;                var str2 = str.substring(0, 1);                if (str2 == "s") {                    return str1 * 1000;                }                else if (str2 == "h") {                    return str1 * 60 * 60 * 1000;                }                else if (str2 == "d") {                    return str1 * 24 * 60 * 60 * 1000;                }            }            // Xiaozhuang cart management.            function XiaozhuangCart() {                // Load initial cart info from cookie.                this.cart_item_map = {};                try {                    var cart_info_string = $.cookie('cart_info');                    if (typeof(cart_info_string) == 'undefined') {                        cart_info_string = '[]';                    }                    console.log('The cart info string is:' + cart_info_string);                    for (var pid_and_num in window.JSON.parse(cart_info_string)) {                        this.cart_item_map[pid_and_num[0]] = pid_and_num[1];                    }                } catch (e) {                    console.log("Get cart info from cookie failed: " + e);                }                this.cart_item_map = {                    2: 10,                };            }            ;            XiaozhuangCart.prototype.addProductToCart = function (pid, num) {                this.cart_item_map[pid] = num;                return this;            };            XiaozhuangCart.prototype.removeProductFromCart = function (pid) {                delete this.cart_item_map[pid];                return this;            };            XiaozhuangCart.prototype.saveToLocal = function () {                var cart_item_list = [];                for (var pid in this.cart_item_map) {                    cart_item_list.push([pid, this.cart_item_map[pid]]);                }                // Save the object to cookie.                $.cookie('cart_info', window.JSON.stringify(cart_item_list), {expires: 30});                console.log("Save cookie to local: " + $.cookie('cart_info'));                return this;            };        </script>    </div>{% endblock %}
1 0
原创粉丝点击