SoFunction
Updated on 2025-04-07

Analysis of the method of realizing shopping cart function by native js+cookie

This article describes the method of implementing shopping cart functions by native js+cookies. Share it for your reference, as follows:

Here, use js+cookie to implement simple shopping cart function.

First of all, it is a simple HTML structure, just to demonstrate the functions.

<ul>
  <li><span>a0001</span><span>shdfi</span><span>¥98.00</span>
<input type="button" value="add to the cart"></li>
  <li><span>a0002</span><span>fbvfgdb</span><span>¥698.00</span>
<input type="button" value="add to the cart"></li>
  <li><span>a0003</span><span>dfdfi</span><span>¥988.00</span>
<input type="button" value="add to the cart"></li>
  <li><span>a0004</span><span>sssi</span><span>¥998.00</span>
<input type="button" value="add to the cart"></li>
  <li><span>a0005</span><span>yyu</span><span>¥98.00</span>
<input type="button" value="add to the cart"></li>
  <li><span>a0006</span><span>sheri</span><span>¥598.00</span>
<input type="button" value="add to the cart"></li>
  <li><span>a0007</span><span>dsfcdhdfi</span><span>¥498.00</span>
<input type="button" value="add to the cart"></li>
  <li><span>sbnm,</span><span>¥698.00</span><input type="button" value="add
 Enter the shopping cart"></li>
</ul>
<a href="Shopping cart view page.html" rel="external nofollow" >View the shopping cart</a>

The following code implements the implementation of adding product information to cookies when clicking the Add button, and the comments are more detailed. In the code, I encapsulate the operation of cookies (set and get as cookieUtil objects, which is convenient for calling).

<script>
    //
    //
    onload = function () {
      var input = ("input");
      //Judge whether there is a cookie, or the first time it is added      var arr = ("car") ? 
(("car")) : [];
      //Travel to add click event to each input element      for (var j = 0; j < ; j++) {
        input[j].onclick = function () {
          var g_id = [0].innerHTML;
          var g_name = [1].innerHTML;
          var g_price = [2].innerHTML;
          //Travel over the cookie to determine whether the product already exists          for (var i = 0; i < ; i++) {
            if (arr[i].g_id == g_id) {
              //The product already exists, the quantity of the product + 1              arr[i].num++;
              break;//End the traversal immediately            }
          }
          //If the value of i is the same as arr length, it is proved that the if conditional statement has not been entered after the traversal ends.          //The product does not exist in the cookie. Create a new product object and add it to the array          if (i == ) {
            var goods = {
              "g_id" : g_id,
              "g_name" : g_name,
              "g_price" : g_price,
              num : 1
            }
            (goods);
          }
          //Serialize the updated array into JSON string and save it to cookie          var date = new Date();
          (() + 10); //Save for ten days  //Save cookies  ("car", (arr), date); 
        }
      }
    }
</script>

Here is the encapsulated cookieUtil object

//cookie Util
var cookieUtil = {
  //Add cookies  setCookie: function (name, value, expires) {
    var cookieText = encodeURIComponent(name) + "=" + 
encodeURIComponent(value);
    if (expires && expires instanceof Date) {
      cookieText += "; expires=" + expires;
    }
    // if (domain) {
    //   cookieText += "; domain=" + domain;
    // }
     = cookieText;
  },
  //Get cookies  getCookie: function (name) {
    var cookieText = decodeURIComponent();
    var cookieArr = ("; ");
    for (var i = 0; i < ; i++) {
      var arr = cookieArr[i].split("=");
      if (arr[0] == name) {
        return arr[1];
      }
    }
    return null;
  },
  //Delete cookies  unsetCookie: function (name) {
     = encodeURIComponent(name) + "=; expires=" + 
new Date(0);
  }
};

The above codes are very easy to understand. The following page is to remove the product information in the cookie.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>View the shopping cart page</title>
  <script src="../"></script>
  <script>
    onload = function () {
      var ul = ("ul")[0];
      var arr = ("car");
      if (arr) {
        arr = (arr);
        // If there is a cookie, it will be taken out and displayed on the page        for (var i = 0; i < ; i++) {
          //Each array element corresponds to a product object          var goods = arr[i];
          var li = ("li");
           = "Product Name:" + goods.g_name + ", product count
 quantity" +  + ", unit price of goods:" + goods.g_price;
          (li);
        }
      } else {
        alert("There is no product in the shopping cart yet!");
      }
    }
  </script>
</head>
<body>
<ul></ul>
</body>
</html>

For more information about JavaScript, readers who are interested in reading this site's special topic:Summary of JavaScript data structure and algorithm techniques》、《Summary of JavaScript traversal algorithm and skills》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript animation effects and techniques》、《Summary of JavaScript Errors and Debugging Skills"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.