Home > Web Front-end > JS Tutorial > body text

How to implement shopping cart function using js+cookie

亚连
Release: 2018-06-19 12:03:53
Original
3196 people have browsed it

This article mainly introduces the method of implementing the shopping cart function with native js cookies, and analyzes the related operating techniques of javascript combined with cookie storage to implement the shopping cart function in the form of examples. Friends in need can refer to this article

The example describes how to implement the shopping cart function using native js cookie. Share it with everyone for your reference, the details are as follows:

Here we use js cookie to implement a simple shopping cart function.

The first is a simple HTML structure, just to demonstrate the function.

<ul>
  <li><span>a0001</span><span>shdfi</span><span>¥98.00</span>
<input type="button" value="加入购物车"></li>
  <li><span>a0002</span><span>fbvfgdb</span><span>¥698.00</span>
<input type="button" value="加入购物车"></li>
  <li><span>a0003</span><span>dfdfi</span><span>¥988.00</span>
<input type="button" value="加入购物车"></li>
  <li><span>a0004</span><span>sssi</span><span>¥998.00</span>
<input type="button" value="加入购物车"></li>
  <li><span>a0005</span><span>yyu</span><span>¥98.00</span>
<input type="button" value="加入购物车"></li>
  <li><span>a0006</span><span>sheri</span><span>¥598.00</span>
<input type="button" value="加入购物车"></li>
  <li><span>a0007</span><span>dsfcdhdfi</span><span>¥498.00</span>
<input type="button" value="加入购物车"></li>
  <li><span>sbnm,</span><span>¥698.00</span><input type="button" value="加
入购物车"></li>
</ul>
<a href="购物车查看页面.html" rel="external nofollow" >查看购物车</a>
Copy after login

The following code is to add the product information to the cookie when the add button is clicked. The comments are more detailed. In the code, I will operate cookies (set and get are encapsulated as cookieUtil object methods for easy calling).

<script>
    //JSON.parse
    //JSON.stringify
    onload = function () {
      var input = document.getElementsByTagName("input");
      //判断是否存在cookie,或是第一次添加
      var arr = cookieUtil.getCookie("car") ? 
JSON.parse(cookieUtil.getCookie("car")) : [];
      //遍历给每个input元素添加点击事件
      for (var j = 0; j < input.length; j++) {
        input[j].onclick = function () {
          var g_id = this.parentNode.children[0].innerHTML;
          var g_name = this.parentNode.children[1].innerHTML;
          var g_price = this.parentNode.children[2].innerHTML;
          //遍历cookie,判断是否已经存在该商品
          for (var i = 0; i < arr.length; i++) {
            if (arr[i].g_id == g_id) {
              //已经存在该商品,商品数量+1
              arr[i].num++;
              break;//立即结束遍历
            }
          }
          //如果i的值与arr长度相同,则证明遍历结束也没有进入过if条件语句,
          //cookie中不存在该商品,新建一个商品对象,并添加到数组中
          if (i == arr.length) {
            var goods = {
              "g_id" : g_id,
              "g_name" : g_name,
              "g_price" : g_price,
              num : 1
            }
            arr.push(goods);
          }
          //把更新后的数组序列化为JSON字符串,保存到cookie中
          var date = new Date();
          date.setDate(date.getDate() + 10); //保存十天
  //保存cookie
  cookieUtil.setCookie("car", JSON.stringify(arr), date); 
        }
      }
    }
</script>
Copy after login

This is the encapsulated cookieUtil object

//cookie Util
var cookieUtil = {
  //添加cookie
  setCookie: function (name, value, expires) {
    var cookieText = encodeURIComponent(name) + "=" + 
encodeURIComponent(value);
    if (expires && expires instanceof Date) {
      cookieText += "; expires=" + expires;
    }
    // if (domain) {
    //   cookieText += "; domain=" + domain;
    // }
    document.cookie = cookieText;
  },
  //获取cookie
  getCookie: function (name) {
    var cookieText = decodeURIComponent(document.cookie);
    var cookieArr = cookieText.split("; ");
    for (var i = 0; i < cookieArr.length; i++) {
      var arr = cookieArr[i].split("=");
      if (arr[0] == name) {
        return arr[1];
      }
    }
    return null;
  },
  //删除cookie
  unsetCookie: function (name) {
    document.cookie = encodeURIComponent(name) + "=; expires=" + 
new Date(0);
  }
};
Copy after login

The above code is very easy to understand. The following page is to take out the product information in the cookie.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>查看购物车页面</title>
  <script src="../Utils.js"></script>
  <script>
    onload = function () {
      var ul = document.getElementsByTagName("ul")[0];
      var arr = cookieUtil.getCookie("car");
      if (arr) {
        arr = JSON.parse(arr);
        //存在cookie则取出来显示到页面上
        for (var i = 0; i < arr.length; i++) {
          //每个数组元素对应的是一个商品对象
          var goods = arr[i];
          var li = document.createElement("li");
          li.innerHTML = "商品名称:" + goods.g_name + ",商品数
量" + goods.num + ",商品单价:" + goods.g_price;
          ul.appendChild(li);
        }
      } else {
        alert("购物车中还不存在商品!");
      }
    }
  </script>
</head>
<body>
<ul></ul>
</body>
</html>
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement sensitive text prompts in Angular

How to implement hidden display in Angular

How to realize left and right sliding of pictures in js

How does BrowserRouter cooperate with react-router server

The above is the detailed content of How to implement shopping cart function using js+cookie. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
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!