This article has shared the specific code for JS to implement the shopping cart function for your reference. The specific content is as follows
3 ways to implement shopping cart
1. Use cookies
Advantages: It does not occupy server resources, it can be saved forever without considering failure
Disadvantages: There is a limit on the number of items purchased. The size of the data stored cannot exceed 2k. If the user disables cookies, there is no way to buy the items. Zhuoyue.com has realized that when the user disables cookies, he can also purchase them.
2. Use session
Advantages: Users can disable cookies and can also shop
Disadvantages: Taking up server resources, you must consider the issue of session failure
3. Utilize the database
Advantages: It can record users' purchasing behavior, facilitate data analysis of users' preferences, and recommend products
Disadvantages: Put too much pressure on the database, if the amount of data is large.
Shopping cart demand analysis
1. You can add products to the shopping cart
2. You can delete items in the shopping cart
3. You can clear the shopping cart
4. You can update the shopping cart products
5. Can be settled
js code
/** * Created by Administrator on 2017/9/3. */ /*** * Shopping cart operation module * */ //Products/*** * @name item * @example item(sku, name, price, quantity) * @params {string} sku product label * @params {string} name The name of the product * @param {number} price * @param {number} quantity The quantity of the product */ function item(sku, name, price, quantity){ = sku; = name; = price; = quantity; } var shopCart = function(window){ "use strict"; //Global variables // note new new Date("2020-12-23") reported an error under ie, and such syntax is not supported var items = [],cartName='kuaidian_shop_cart',expires = new Date( new Date().getTime()+86400000*30 ) ,debug = true,decimal = 2; var options = { 'cartName' : cartName, //The name of the cookie 'expires' : expires, //Time of invalidation of cookies 'debug' : debug, //Whether to print debug information 'decimal' : decimal, //The number of digits after the decimal point is accurate 'callback' : undefined }; //Exposed interface method to external return { inited : false, init: function(option){ //Discern whether the user disables cookies if(! ){ alert('Your browser does not support cookies and cannot use the shopping cart! , please set allow to set cookies. '); return false; } //Get data from the shopping cart from the cookie = true; if(option){ extend(options,option); } var cookie = getCookie(); if(typeof cookie === 'undefined'){ setCookie(,'',); }else{ // Use & to separate each item, use|segment between the properties of the item var cookie = getCookie(); if(cookie){ var cItems = ('&'); for(var i=0,l=;i<l;i++){ var cItem = cItems[i].split('|'); var item = {}; = cItem[0] || ''; = cItem[1] || ''; = cItem[2] || ''; = cItem[3] || ''; (item); }; }; }; }, findItem: function(sku){//Finish products according to Sku mark //If sku is not provided, then all items are returned if(sku){ for(var i=0,l=;i<l;i++){ var item = items[i]; if( === sku){ return item; } } return undefined; }else{ return items; } }, getItemIndex : function(sku){ //Get item subscript in items array for(var i=0,l=;i<l;i++){ var item = items[i]; if( == sku){ return i; } } //Not found to return -1 return -1; }, addItem: function(item){ //Add a new item to the shopping cart //Add a product if(()){ if(){ _log('The product already exists'); return false; } } (item); _saveCookie(); return true; }, delItem: function(sku){ //Delete an item from the shopping cart //Delete a product var index = (sku); if(index > -1){ (index,1); _saveCookie(); }else{ if(){ _log('The product does not exist'); return false; } } }, updateQuantity: function(item){ //Update quantity of products //Update a product var index = (); if(index > -1){ items[index].quantity = ; _saveCookie(); }else{ if(){ _log('The product does not exist'); return false; } } }, emptyCart: function(){ //Clear the array = 0; _saveCookie(); }, checkout: function(){ //Click the callback function after settlement if(){ (); } }, getTotalCount: function(sku){ //Get the number of items in the shopping cart. If the id of a certain item is transmitted, then the quantity of items will be returned. var totalCount = 0; if(sku){ totalCount = (typeof (sku) === 'undefined' ? 0 : (sku).quantity ); }else{ for(var i=0,l=;i<l;i++){ totalCount += (parseInt(items[i].quantity) === 'NaN' ? 0 : parseInt(items[i].quantity )) ; } } return totalCount; }, getTotalPrice : function(sku){ //Get the total price of the shopping cart product. If the id of a product is transmitted, then the total price of the product will be returned. var totalPrice = 0.0; if(sku){ var num = parseInt((typeof (sku) === 'undefined' ? 0 : (sku).quantity )), price = parseFloat((typeof (sku) === 'undefined' ? 0 : (sku).price )); num = num=== 'NaN' ? 0 : num; price = price === 'NaN' ? 0 : price; totalPrice = price * num; }else{ for(var i=0,l=;i<l;i++){ totalPrice += (parseFloat(items[i].price ) * parseInt(items[i].quantity)); } } return (); }, getCookie : getCookie, setCookie : setCookie }; /** * Set cookies * @name setCookie * @example setCookie(name, value[, options]) * @params {string} name The key name of the cookie needs to be set * @params {string} value requires setting the value of the cookie * @params {string} [path] cookie path * @params {Date} [expires] cookie expiration time */ function setCookie(name, value, options) { options = options || {}; var expires = || null; var path = || "/"; var domain = || ; var secure = || null; /** = name + "=" + escape(value) + ((expires) ? "; expires=" + () : "") + "; path=" + path + "; domain=" + domain ; + ((secure) ? "; secure" : ""); */ var str = name + "=" + encodeURIComponent(value) + ((expires) ? "; expires=" + () : "") + "; path=/"; = str; }; /** * Get the value of the cookie * @name getCookie * @example getCookie(name) * @param {string} name The key name of the cookie needs to be obtained * @return {string|null} The obtained cookie value, return null when it is not available */ function getCookie(name) { var arr = (new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) { return decodeURIComponent(arr[2]); } return undefined; }; //*********************Private method*********************/ function _saveCookie(){ var i=0,l=; if(l>0){ var tItems = []; for(;i<l;i++){ var item = items[i]; tItems[i] = + '|' + + '|' + + '|' + ; }; var str = ('&'); setCookie(, str, {expires:}); }else{ setCookie(, '', {expires:}); } }; //****************** Tool Method*********************/ //Show debugging information function _log(info){ if(typeof console != 'undefined'){ (info); } }; //Inheritance attributes function extend(destination, source) { for ( var property in source) { destination[property] = source[property]; } }; }(typeof window === 'undifined' ? this: window);
Simple call to HTML pages
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script type="text/javascript" src="./"></script> <script> ({ 'decimal' : 4 }); var a = new item('aa','bb',12,22); (a); //Add products to shopping cart, parameter item ('12345'); //Delete the product from the shopping cart, parameter squ// (); // Clear the shopping cart = 4; alert(()); //Get the number in the shopping cart, parameter squ ();//Finding products according to sku marks, parameters squ //If sku is not provided, then all items are returned ('aa') //Get the item's array subscript, parameter squ (a) //Update the quantity of the product, parameter item ()//Get the number of items in the shopping cart. If the id of a certain item is transmitted, then the quantity of the item will be returned, parameter squ </script> </body> </html>
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.