js實(shí)現(xiàn)購(gòu)物車功能
本文實(shí)例為大家分享了js實(shí)現(xiàn)購(gòu)物車功能的具體代碼,供大家參考,具體內(nèi)容如下
購(gòu)物車實(shí)現(xiàn)3種方式
1、利用cookie
優(yōu)點(diǎn):不占用服務(wù)器資源,可以永遠(yuǎn)保存,不用考慮失效的問(wèn)題
缺點(diǎn): 對(duì)購(gòu)買商品的數(shù)量是有限制的,存放數(shù)據(jù)的大小 不可以超過(guò)2k,用戶如果禁用cookie那么就木有辦法購(gòu)買商品,卓越網(wǎng)實(shí)現(xiàn)了用戶當(dāng)用戶禁用cookie,也可以購(gòu)買。
2、利用 session
優(yōu)點(diǎn):用戶禁用cookie,也可以購(gòu)物
缺點(diǎn):占用服務(wù)器資源,要考慮session失效的問(wèn)題
3、利用數(shù)據(jù)庫(kù)
優(yōu)點(diǎn):可以記錄用戶的購(gòu)買行為,便于數(shù)據(jù)分析用戶的喜好,推薦商品
缺點(diǎn):給數(shù)據(jù)庫(kù)造成太大的壓力,如果數(shù)據(jù)量很大的話。
購(gòu)物車需求分析
1、可以添加商品到購(gòu)物車中
2、可以刪除購(gòu)物車中的商品
3、可以清空購(gòu)物車
4、可以更新購(gòu)物車的商品
5、可以結(jié)算
js代碼
/** * Created by Administrator on 2017/9/3. */ /*** * 購(gòu)物車操作模塊 * */ //商品類 /*** * @name item * @example item(sku, name, price, quantity) * @params {string} sku 商品的標(biāo)示 * @params {string} name 商品的名字 * @param {number} price 商品的價(jià)格 * @param {number} quantity 商品的數(shù)量 */ function item(sku, name, price, quantity){ this.sku = sku; this.name = name; this.price = price; this.quantity = quantity; } var shopCart = function(window){ "use strict"; //全局變量 // note new new Date("2020-12-23") 在ie下面報(bào)錯(cuò),不支持這樣的語(yǔ)法 var items = [],cartName='kuaidian_shop_cart',expires = new Date( new Date().getTime()+86400000*30 ) ,debug = true,decimal = 2; var options = { 'cartName' : cartName, //cookie的名字 'expires' : expires, //cookie失效的時(shí)間 'debug' : debug, //是否打印調(diào)試信息 'decimal' : decimal, //錢的精確到小數(shù)點(diǎn)后的位數(shù) 'callback' : undefined }; //暴露給外部的接口方法 return { inited : false, init: function(option){ //判斷用戶是否禁用cookie if(!window.navigator.cookieEnabled ){ alert('您的瀏覽器不支持cookie無(wú)法使用購(gòu)物車!,請(qǐng)?jiān)O(shè)置允許設(shè)置cookie。'); return false; } //從cookie中獲取購(gòu)物車中的數(shù)據(jù) this.inited = true; if(option){ extend(options,option); } var cookie = getCookie(options.cartName); if(typeof cookie === 'undefined'){ setCookie(options.cartName,'',options.expires); }else{ //每個(gè)item之間用&分開,item的屬性之間用|分割 var cookie = getCookie(options.cartName); if(cookie){ var cItems = cookie.split('&'); for(var i=0,l=cItems.length;i<l;i++){ var cItem = cItems[i].split('|'); var item = {}; item.sku = cItem[0] || ''; item.name = cItem[1] || ''; item.price = cItem[2] || ''; item.quantity = cItem[3] || ''; items.push(item); }; }; }; }, findItem: function(sku){//根據(jù)sku標(biāo)示查找商品 //如果木有提供sku,則返回所有的item if(sku){ for(var i=0,l=items.length;i<l;i++){ var item = items[i]; if(item.sku === sku){ return item; } } return undefined; }else{ return items; } }, getItemIndex : function(sku){ //獲取item在items的數(shù)組下標(biāo) for(var i=0,l=items.length;i<l;i++){ var item = items[i]; if(item.sku == sku){ return i; } } //木有找到返回-1 return -1; }, addItem: function(item){ //增加一個(gè)新商品到購(gòu)物車 //添加一個(gè)商品 if(this.findItem(item.sku)){ if(options.debug){ _log('商品已經(jīng)存在了'); return false; } } items.push(item); _saveCookie(); return true; }, delItem: function(sku){ //從購(gòu)物車中刪除一個(gè)商品 //刪除一個(gè)商品 var index = this.getItemIndex(sku); if(index > -1){ items.splice(index,1); _saveCookie(); }else{ if(options.debug){ _log('商品不存在'); return false; } } }, updateQuantity: function(item){ //更新商品的數(shù)量 //更新一個(gè)商品 var index = this.getItemIndex(item.sku); if(index > -1){ items[index].quantity = item.quantity; _saveCookie(); }else{ if(options.debug){ _log('商品不存在'); return false; } } }, emptyCart: function(){ //清空數(shù)組 items.length = 0; _saveCookie(); }, checkout: function(){ //點(diǎn)擊結(jié)算后的回調(diào)函數(shù) if(options.callback){ options.callback(); } }, getTotalCount: function(sku){ //獲取購(gòu)物車商品的數(shù)量,如果傳某個(gè)商品的id,那么就返回該商品的數(shù)量 var totalCount = 0; if(sku){ totalCount = (typeof this.findItem(sku) === 'undefined' ? 0 : this.findItem(sku).quantity ); }else{ for(var i=0,l=items.length;i<l;i++){ totalCount += (parseInt(items[i].quantity) === 'NaN' ? 0 : parseInt(items[i].quantity )) ; } } return totalCount; }, getTotalPrice : function(sku){ //獲取購(gòu)物車商品的總價(jià)格 ,如果傳某個(gè)商品的id,那么就返回該商品的總價(jià)格 var totalPrice = 0.0; if(sku){ var num = parseInt((typeof this.findItem(sku) === 'undefined' ? 0 : this.findItem(sku).quantity )), price = parseFloat((typeof this.findItem(sku) === 'undefined' ? 0 : this.findItem(sku).price )); num = num=== 'NaN' ? 0 : num; price = price === 'NaN' ? 0 : price; totalPrice = price * num; }else{ for(var i=0,l=items.length;i<l;i++){ totalPrice += (parseFloat(items[i].price ) * parseInt(items[i].quantity)); } } return totalPrice.toFixed(options.decimal); }, getCookie : getCookie, setCookie : setCookie }; /** * 設(shè)置cookie * @name setCookie * @example setCookie(name, value[, options]) * @params {string} name 需要設(shè)置Cookie的鍵名 * @params {string} value 需要設(shè)置Cookie的值 * @params {string} [path] cookie路徑 * @params {Date} [expires] cookie過(guò)期時(shí)間 */ function setCookie(name, value, options) { options = options || {}; var expires = options.expires || null; var path = options.path || "/"; var domain = options.domain || document.domain; var secure = options.secure || null; /** document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + "; path=" + path + "; domain=" + domain ; + ((secure) ? "; secure" : ""); */ var str = name + "=" + encodeURIComponent(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + "; path=/"; document.cookie = str; }; /** * 獲取cookie的值 * @name getCookie * @example getCookie(name) * @param {string} name 需要獲取Cookie的鍵名 * @return {string|null} 獲取的Cookie值,獲取不到時(shí)返回null */ function getCookie(name) { var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) { return decodeURIComponent(arr[2]); } return undefined; }; //***********************私有方法********************/ function _saveCookie(){ var i=0,l=items.length; if(l>0){ var tItems = []; for(;i<l;i++){ var item = items[i]; tItems[i] = item.sku + '|' +item.name + '|' + item.price + '|' + item.quantity; }; var str = tItems.join('&'); setCookie(options.cartName, str, {expires:options.expires}); }else{ setCookie(options.cartName, '', {expires:options.expires}); } }; //***********************工具方法********************/ //顯示調(diào)試信息 function _log(info){ if(typeof console != 'undefined'){ console.log(info); } }; //繼承屬性 function extend(destination, source) { for ( var property in source) { destination[property] = source[property]; } }; }(typeof window === 'undifined' ? this: window);
HTML頁(yè)面簡(jiǎn)單調(diào)用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script type="text/javascript" src="./shop.js"></script> <script> shopCart.init({ 'decimal' : 4 }); var a = new item('aa','bb',12,22); shopCart.addItem(a); //添加商品到購(gòu)物車,參數(shù)item shopCart.delItem('12345'); //從購(gòu)物車中刪除商品,參數(shù)squ // shopCart.emptyCart(); //清空購(gòu)物車 item.quantity = 4; alert(shopCart.getTotalPrice()); //獲取購(gòu)物車中的數(shù)量,參數(shù)squ shopCart.findItem();//根據(jù)sku標(biāo)示查找商品,參數(shù)squ //如果木有提供sku,則返回所有的item shopCart.getItemIndex('aa') //獲取item在items的數(shù)組下標(biāo),參數(shù)squ shopCart.updateQuantity(a) //更新商品的數(shù)量,參數(shù)item shopCart.getTotalCount()//獲取購(gòu)物車商品的數(shù)量,如果傳某個(gè)商品的id,那么就返回該商品的數(shù)量,參數(shù)squ </script> </body> </html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- vuejs手把手教你寫一個(gè)完整的購(gòu)物車實(shí)例代碼
- js購(gòu)物車實(shí)現(xiàn)思路及代碼(個(gè)人感覺不錯(cuò))
- JavaScript編寫一個(gè)簡(jiǎn)易購(gòu)物車功能
- Javascript實(shí)現(xiàn)購(gòu)物車功能的詳細(xì)代碼
- js實(shí)現(xiàn)簡(jiǎn)單的購(gòu)物車有圖有代碼
- Jsp+Servlet實(shí)現(xiàn)購(gòu)物車功能
- 原生js模擬淘寶購(gòu)物車項(xiàng)目實(shí)戰(zhàn)
- Javascript操縱Cookie實(shí)現(xiàn)購(gòu)物車程序
- 簡(jiǎn)單的前端js+ajax 購(gòu)物車框架(入門篇)
- JavaScript實(shí)現(xiàn)淘寶購(gòu)物件數(shù)選擇
相關(guān)文章
使用bootstrap typeahead插件實(shí)現(xiàn)輸入框自動(dòng)補(bǔ)全之問(wèn)題及解決辦法
這篇文章主要介紹了使用bootstrap typeahead插件實(shí)現(xiàn)輸入框自動(dòng)補(bǔ)全之問(wèn)題及解決辦法的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-07-07JavaScript中l(wèi)ayer關(guān)閉指定彈出窗口方法總結(jié)
這篇文章主要給大家介紹了關(guān)于JavaScript中l(wèi)ayer關(guān)閉指定彈出窗口方法的相關(guān)資料,layer是layui的一個(gè)彈出層組件,但是可以作為獨(dú)立組件使用,需要的朋友可以參考下2023-10-10微信小程序 數(shù)據(jù)緩存實(shí)現(xiàn)方法詳解
這篇文章主要介紹了微信小程序 數(shù)據(jù)緩存實(shí)現(xiàn)方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08JavaScript toUpperCase()方法使用詳解
這篇文章主要為大家詳細(xì)介紹了JavaScript toUpperCase()方法的使用技巧,感興趣的小伙伴們可以參考一下2016-08-08