How to implement shopping cart function using js+cookie
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>
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>
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); } };
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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

Practical tutorial: Detailed explanation of the shopping cart function with PHP and MySQL. The shopping cart function is one of the common functions in website development. Through the shopping cart, users can easily add the goods they want to buy to the shopping cart, and then proceed with settlement and payment. In this article, we will detail how to implement a simple shopping cart function using PHP and MySQL and provide specific code examples. To create a database and data table, you first need to create a data table in the MySQL database to store product information. The following is a simple data table

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese
