国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

js實現購物車功能

2024-05-06 15:33:26
字體:
來源:轉載
供稿:網友

本文實例為大家分享了js實現購物車功能的具體代碼,供大家參考,具體內容如下

購物車實現3種方式

1、利用cookie

優點:不占用服務器資源,可以永遠保存,不用考慮失效的問題
缺點: 對購買商品的數量是有限制的,存放數據的大小 不可以超過2k,用戶如果禁用cookie那么就木有辦法購買商品,卓越網實現了用戶當用戶禁用cookie,也可以購買。

2、利用 session

優點:用戶禁用cookie,也可以購物
缺點:占用服務器資源,要考慮session失效的問題

3、利用數據庫

優點:可以記錄用戶的購買行為,便于數據分析用戶的喜好,推薦商品
缺點:給數據庫造成太大的壓力,如果數據量很大的話。

購物車需求分析

1、可以添加商品到購物車中

2、可以刪除購物車中的商品

3、可以清空購物車

4、可以更新購物車的商品

5、可以結算

js代碼

/** * Created by Administrator on 2017/9/3. *//*** * 購物車操作模塊 * *///商品類/*** * @name item * @example  item(sku, name, price, quantity) * @params {string} sku 商品的標示 * @params {string} name 商品的名字 * @param {number} price 商品的價格 * @param {number} quantity 商品的數量 */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下面報錯,不支持這樣的語法  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失效的時間    'debug' : debug, //是否打印調試信息    'decimal' : decimal, //錢的精確到小數點后的位數    'callback' : undefined  };  //暴露給外部的接口方法  return {    inited : false,    init: function(option){      //判斷用戶是否禁用cookie      if(!window.navigator.cookieEnabled ){        alert('您的瀏覽器不支持cookie無法使用購物車!,請設置允許設置cookie。');        return false;      }      //從cookie中獲取購物車中的數據      this.inited = true;      if(option){        extend(options,option);      }      var cookie = getCookie(options.cartName);      if(typeof cookie === 'undefined'){        setCookie(options.cartName,'',options.expires);      }else{        //每個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){//根據sku標示查找商品      //如果木有提供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的數組下標      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){ //增加一個新商品到購物車      //添加一個商品      if(this.findItem(item.sku)){        if(options.debug){          _log('商品已經存在了');          return false;        }      }      items.push(item);      _saveCookie();      return true;    },    delItem: function(sku){ //從購物車中刪除一個商品      //刪除一個商品      var index = this.getItemIndex(sku);      if(index > -1){        items.splice(index,1);        _saveCookie();      }else{        if(options.debug){          _log('商品不存在');          return false;        }      }    },    updateQuantity: function(item){ //更新商品的數量      //更新一個商品      var index = this.getItemIndex(item.sku);      if(index > -1){        items[index].quantity = item.quantity;        _saveCookie();      }else{        if(options.debug){          _log('商品不存在');          return false;        }      }    },    emptyCart: function(){      //清空數組      items.length = 0;      _saveCookie();    },    checkout: function(){      //點擊結算后的回調函數      if(options.callback){        options.callback();      }    },    getTotalCount: function(sku){      //獲取購物車商品的數量,如果傳某個商品的id,那么就返回該商品的數量      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){      //獲取購物車商品的總價格 ,如果傳某個商品的id,那么就返回該商品的總價格      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  };  /**   * 設置cookie   * @name setCookie   * @example    setCookie(name, value[, options])   * @params {string} name 需要設置Cookie的鍵名   * @params {string} value 需要設置Cookie的值   * @params {string} [path] cookie路徑   * @params {Date} [expires] cookie過期時間   */  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值,獲取不到時返回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});    }  };  //***********************工具方法********************/  //顯示調試信息  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);            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 三台县| 许昌市| 峨眉山市| 吴桥县| 德庆县| 若尔盖县| 集贤县| 安达市| 荔浦县| 威信县| 西华县| 博湖县| 枣庄市| 石楼县| 徐汇区| 宁城县| 东安县| 巢湖市| 互助| 崇州市| 东平县| 离岛区| 涡阳县| 五莲县| 永州市| 游戏| 耒阳市| 洛浦县| 岫岩| 察雅县| 柳州市| 兖州市| 枞阳县| 介休市| 习水县| 海晏县| 奇台县| 盱眙县| 叶城县| 潼南县| 蒙自县|