map dictionary, stored cookie, switch accounts, showing different commodities cart

1: Home

  • 1, static html5 + css to do basic style

html5,css,jQery, sass

  • 2, jsonp way to introduce simulations src json data // data used here take jsonp, and details have to use ajax

Json traversal data:


let data = like['msg']; //获取json数据列表
let like_lists = document.querySelector('.like_lists'); //获取ul便签


//通过循环遍历出后台收据,每循环一次就通过js的dom生成节点,依次插入标签中。并附上类名与id。

2: Jump details ajax异步请求

  • Key: indexOf, continue ajax

//首页给a标签绑定一个宝贝的唯一id,点击跳转详情页,通过herf发送这条数据
a1.href = `./front/pages/detail_page.html?id=${itemId}`;

//详情接受地址数据
function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg); //匹配目标参数
            if (r != null) return unescape(r[2]);
            return null; //返回参数值
}
//ajax请求json数据,indexOf判断列表是否包含次数据。
for (let i = 0; i < data.msg.length; i++) {
    // let data = xq['msg'][i]['itemId'];
    if (data.msg[i]['itemId'].indexOf(id) === -1) { /不包含id
        continue; //跳出  //多个
        //如果不包含就跳出,不打印。*注意要添加循环列表的索引值i
    }
}

3: Details page traversal

  • Use the jQuery sass gulp

FIG main part, small box image, for each cycle through the img src replace the image. When the mouse into the small box, big box and magnifying glass in the img src replaced src small box.


for (let i = 0; i < imgBtn.length; i++) {
    imgBtn[i].onmouseover = function() {
        oBig.children[0].src = imgBtn[i].childr.src;
        oSmall.children[0].src = imgBtn[i].chi[0].src;
    }
}


let imgBtn = document.querySelectorAll('.samll_box'); //5个小盒子
let oSmall = document.getElementById('oSmall'); //盒子  里面有img
let oBig = document.getElementById('oBig');
oSmall.children[0].src = imgBtn[0].children[0].src;//默认5小盒子里的第一个展示在大盒子上

4: registration page 模块化

  • Use the PHP mysql jQuery sass gulp ajax localStorage

registered:

  • JQuery plugin to use, easy to get the label, and it's an easy choice.
  • Focus trigger event when the mouse get input focus, prompted by the positive input is required
  • Leaving blur triggers mouse events to determine inpu of val () is empty, meets regularity conditions, if the conditions are in line with the requirements of regular cut is not empty then prompts the user name can be registered
  • When you click Register, ajax submit the background if the user has not registered the name returns a prompt "the user name has been registered."
  • Once registered, use setTimeout () delay 3s to open the login screen

log in:

  • JQuery plugin to use, easy to get the label, and it's an easy choice.
  • Constructors, inheritance through prototype method, logon trigger event, the implementation function. Determine whether the correct user name and password
  • Successful login, the user name saved locally, and jump Home

 localStorage.setItem("username", $('#username').val());
  • Home jump when loading onloadfunction triggers the following gets saved locally successful login user name and show

 load_data() {
        var theme = localStorage.getItem("username");
        if (theme == null || theme == "") {
            $('.login_show').hide();
            $('.unlogin').show();

        } else {
            $('.login_show').show().children('.login_name').text(theme).css('color', 'red')
            $('.unlogin').hide();
        }

    }
  • When click quit, triggering functions, clear your local user name and load_data()functions, partial refresh

exitu() {
        localStorage.removeItem("username");
        //刷新部分
        this.load_data();
     }

5: Adding cart ideas

  • Use the jQuery sass gulp ajax cookie

  • Click on details page 购物车triggered the event. Execution of the function, the second baby into cookie id save, and prompts to add cart Complete

  • When the user clicks 进入购物车the button. Trigger events, execute the function, the value of the cookie value to traverse it, request json file with ajax asynchronous, indexOf judgment screening. It will include commodity prices and Photo Gallery page.

  • Written calculator. Conduct quantity, price calculations.

important point:
最后会与结算的计算器调用的函数必须要在ajax里面写或者调用,不然获取不了那些生成的元素,从而得不到里面的数据!


购物车进阶版本

  • The above ideas, after triggering Add to Cart events, merchandise directly into the cookie, not tied to a user name, user experience is poor. The following is a user id and commodity bind idea!

Dictionary object methods

var dic={
    admin:[1,2,3],
    nihaoya:[4,5,6]
}
// 1、获取本地json串 -- String str = Local.getItem("one");"{admin:["1","2","3"],  admin1:[shopcar],admin2:[]}"
// 2、把json串转换成字典 -- Map dic = JSONObject.parse(str);  {admin:["1","2","3"],admin1:[shopcar],admin2:[]}
// 3、获取自己的购物车数据 -- List shopCar = dic[admin];       ["1","2","3"]
// 4、把需要添加到购物车的商品赋值给shopCar -- shopCar.add(data);["1","2","3","4"]
// 5、把dic转换成json -- String json = JSONObject.toJSONString(dic); {admin:["1","2","3"],admin1:[shopcar],admin2:[]}"
// 6、保存json到本地  -- Local.saveItem("one",dic);
var locaname = localStorage.getItem('username');
var li = []; //购物车
var dictionary = {}; //创建一个空对象
if (!getCookie(0)) {
    // li = dictionary[locaname];
    if (dictionary[locaname] === undefined) {
        dictionary[locaname] = li;

} else {
    var dic = JSON.parse(getCookie(0));cookie 并解析
    // li = dic[locaname]; //将对应字典里key的v值给自己的购物车
    if (dic[locaname] !== undefined) {
        li = dic[locaname];
    }
}

if (!getCookie(0)) {

    li.push(data.msg[i]['itemId']);
    dictionary[locaname] = li;
    var dobj = JSON.stringify(dictio

} else {

    li.push(data.msg[i]['itemId']);
    dic[locaname] = li;
    var dobj = JSON.stringify(dic);

}

// li.push(data.msg[i]['itemId']);
// setCookie(i, data.msg[i]['itemId'
setCookie(0, dobj, 7);
  • 注意点: Function performed at the beginning, to determine whether the cookie has a stored value, if any, will be assigned to dic, If you do not have to declare an empty object, and then assign the list it is necessary to determine the trigger event!. Storage json, when reading the same name.


  $.ajax({
                //请求方式为get
                type: "GET",
                //json文件位置
                url: "../../data/xqq.json",
                //返回数据格式为json
                dataType: "json",
                //请求成功完成后要执行的方法

                success: function (data) {

                    // console.log(dictionary[locaname]);
                    // 1、获取本地数据dictionary {name1:[shopcar],name2:[]}
                    // 2、获取自己的购物车数据 dictionary[locaname]
                    // 3、赋值给一个list var li=dictionary[locaname]
                    // 4、list插入需要加入到购物车的数据 li。add(data)
                    // 5、把list赋值给自己的购物车数据 dictionary[locaname]=li
                    // 6、保存dictionary local。save      

                    // 1、获取本地json串 -- String str = Local.getItem("one");             "{admin:["1","2","3"],admin1:[shopcar],admin2:[]}"
                    // 2、把json串转换成字典 -- Map dic = JSONObject.parse(str);            {admin:["1","2","3"],admin1:[shopcar],admin2:[]}
                    // 3、获取自己的购物车数据 -- List shopCar = dic[admin];                 ["1","2","3"]
                    // 4、把需要添加到购物车的商品赋值给shopCar -- shopCar.add(data);          ["1","2","3","4"]
                    // 5、把dic转换成json -- String json = JSONObject.toJSONString(dic);    "{admin:["1","2","3"],admin1:[shopcar],admin2:[]}"
                    // 6、保存json到本地  -- Local.saveItem("one",dic);

                    var locaname = localStorage.getItem('username');
                    var li = []; //购物车
                    var dictionary = {}; //创建一个空对象 存数据

                    if (!getCookie(0)) {
                        // li = dictionary[locaname];
                        if (dictionary[locaname] === undefined) {
                            dictionary[locaname] = li;
                        }

                    } else {
                        var dic = JSON.parse(getCookie(0)); //获取cookie 并解析
                        // li = dic[locaname]; //将对应字典里key的value赋值给自己的购物车
                        if (dic[locaname] !== undefined) {
                            li = dic[locaname];
                        }
                    }


                    for (let i = 0; i < data.msg.length; i++) {
                        // let data = xq['msg'][i]['itemId'];

                        if (data.msg[i]['itemId'].indexOf(id) === -1) { //data不包含id
                            continue; //跳出  //多个
                            //如果不包含就跳出,不打印。*注意要添加循环列表的索引值i
                        }
                        // 遍历详情页
                        // console.log(data.msg[i]['goods_gallery_urls'][2]);
                        for (let a = 0; a < 5; a++) {
                            let img1 = document.createElement('img');
                            img1.className = 'img11';
                            img1.src = data.msg[i]['goods_gallery_urls'][a]
                            imgBox[a].appendChild(img1)
                        }
                        // 标题
                        let productMainName = document.getElementById('productMainName');
                        productMainName.innerHTML = data.msg[i]['goods_name'];
                        // 提示
                        let buy21 = document.getElementById('buy21');
                        buy21.innerHTML = data.msg[i]['goods_desc'];

                        let goods_eval_score = document.getElementById('goods_eval_score');
                        goods_eval_score.innerHTML = data.msg[i]['payPoint'];

                        let category_id = document.getElementById('category_id');
                        category_id.innerHTML = data.msg[i]['srcPoint']

                        // 店名
                        $('.store_name').text(data.msg[i]['mall_name']);

                        // 点击触发事件存储本地
                        $('.store_car').click(() => {

                            if (!getCookie(0)) {

                                li.push(data.msg[i]['itemId']);
                                dictionary[locaname] = li;
                                var dobj = JSON.stringify(dictionary);

                            } else {
                                li.push(data.msg[i]['itemId']);
                                dic[locaname] = li;
                                var dobj = JSON.stringify(dic);

                            }

                            // li.push(data.msg[i]['itemId']);
                            // setCookie(i, data.msg[i]['itemId'], 7);

                            setCookie(0, dobj, 7);

                            alert('加入购物车成功,付款请进入购物车')

                        })

                    }


                    // dictionary[locaname] = [dakhadsdhksa, adajksjlkads, 3]

                    // var a = ['sas', 'sa']
                    // a.push('assa')
                    // dictionary[locaname] = a;


                    // var keys = [];
                    // dictionary.locaname = [12, 32, 54]
                    // for (var key in dictionary) {
                    //     keys.push(key);
                    // }
                    // dictionary["locaname"].push(77);

                    // console.log(dictionary);

                    // 详情主图
                    let imgBtn = document.querySelectorAll('.samll_box'); //5个小盒子
                    let oSmall = document.getElementById('oSmall'); //获取盒子  里面有img
                    let oBig = document.getElementById('oBig');

                    oSmall.children[0].src = imgBtn[0].children[0].src; //默认5小盒子里的第一个展示在大盒子上

                    for (let i = 0; i < imgBtn.length; i++) {
                        imgBtn[i].onmouseover = function () {
                            oBig.children[0].src = imgBtn[i].children[0].src;
                            oSmall.children[0].src = imgBtn[i].children[0].src;
                        }
                    }


                }
            });
        });
//购物车js

 $.ajax({
        type: "GET",
        // url: "../../data/like_like.json",
        url: "../../data/like_like.json",
        data: "data",
        dataType: "json",
        success: function(response) {
            let username = localStorage.getItem('username'); //本地名


            let dic = JSON.parse(getCookie(0)); //json对象
            console.log(dic);

            var keys = []; //遍历dic长度

            for (var key in dic) {
                keys.push(key);
            }


            if (keys.indexOf(username) == -1) {
                $('.rember').show();
                $('.pay').hide();

            } else {
                $('.pay').show();

                let lkel = response.msg.length;

                // strc.length 
                // dic[username].length //当前用户名里面的value值

                for (let a = 0; a < dic[username].length; a++) { //循环遍历value值

                    // var arr = strc[a].split('=')[1] //arr=cookie的
                    var arr = dic[username][a];

                    for (let i = 0; i < lkel; i++) { //循环遍历json文件 
                        if (response.msg[i]['itemId'].indexOf(arr) === -1) { //json文件里是否包含dic[username]里面的value
                            continue;
                        }
                        // console.log(response.msg[i]['nick']);
                        // console.log(response.msg[i]['icon']);

                        let li1 = document.createElement('li');
                        li1.className = 'carlis';
                        $('.shop_lis').append(li1);
                        let img1 = document.createElement('img');
                        img1.src = response.msg[i]['icon'];
                        img1.className = 'goods_img';

                        li1.append(img1);

                        let p1 = document.createElement('p');
                        p1.innerHTML = response.msg[i]['title'];
                        li1.append(p1);
                        // var p1 = $("<p></p>").text(response.msg[i]['title']);

                        let div1 = document.createElement('div');
                        div1.className = 'goods_bottom';
                        div1.innerHTML = '¥';
                        li1.append(div1);

                        let span1 = document.createElement('span');
                        span1.className = 'goods_price';
                        span1.innerHTML = response.msg[i]['srcPoint'];

                        div1.append(span1)

                        let div_num = document.createElement('div');
                        div_num.className = 'num';
                        div1.append(div_num);

                        let div_minus = document.createElement('div');
                        let div_plus = document.createElement('div');
                        let span2 = document.createElement('span');
                        div_minus.innerHTML = '-';
                        div_plus.innerHTML = '+';
                        span2.innerHTML = '0';
                        div_minus.className = 'minus';
                        div_plus.className = 'plus';


                        div_num.append(div_minus);
                        div_num.append(span2);
                        div_num.append(div_plus);

                    }

                }
            }

            $(".plus").click(function() {
                var num = $(this).parent().children("span");
                //单品数量增加

                num.text(parseInt(num.text()) + 1);
                //商品总数增加
                var totalNum = parseInt($(".totalNum").text());
                totalNum++
                $(".totalNum").text(totalNum);
                //计算总价
                var goods_price = parseFloat($(this).parent().parent().children(".goods_price").text());
                $(".totalPrice").text(parseFloat($(".totalPrice").text()) + goods_price);
            });

            //点击减少按钮触发事件
            $(".minus").click(function() {
                var num = $(this).parent().children("span");
                if (parseInt(num.text())) {
                    num.text(parseInt(num.text()) - 1);
                    var totalNum = parseInt($(".totalNum").text());
                    totalNum--
                    $(".totalNum").text(totalNum);
                    var goods_price = parseFloat($(this).parent().parent().children(".goods_price").text());
                    $(".totalPrice").text(parseFloat($(".totalPrice").text()) - goods_price);
                } else {
                    num.text("0");
                }

                // console.log(parseInt(num.text()));


            });

            //点击付款
            $('#pay_money').click(() => {
                console.log($('.totalPrice').text());

                if ($('.totalPrice').text() === '00') {
                    alert('请输入商品数量');
                } else {
                    $('.pay_photo').show(1000);

                }

            })
            $('#pay_close').click(() => {
                $('.pay_photo').hide();
            })

        }
    });

Guess you like

Origin www.cnblogs.com/wangqingjiu/p/11104544.html