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.
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).
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.
查看购物车页面
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!