视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001 知道1 知道21 知道41 知道61 知道81 知道101 知道121 知道141 知道161 知道181 知道201 知道221 知道241 知道261 知道281
问答文章1 问答文章501 问答文章1001 问答文章1501 问答文章2001 问答文章2501 问答文章3001 问答文章3501 问答文章4001 问答文章4501 问答文章5001 问答文章5501 问答文章6001 问答文章6501 问答文章7001 问答文章7501 问答文章8001 问答文章8501 问答文章9001 问答文章9501
js实现购物车功能
2020-11-27 22:13:06 责编:小OO
文档

本文实例为大家分享了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);

HTML页面简单调用

<!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); //添加商品到购物车,参数item
 shopCart.delItem('12345'); //从购物车中删除商品,参数squ
// shopCart.emptyCart(); //清空购物车
 item.quantity = 4;
 alert(shopCart.getTotalPrice()); //获取购物车中的数量,参数squ


 shopCart.findItem();//根据sku标示查找商品,参数squ
 //如果木有提供sku,则返回所有的item
 shopCart.getItemIndex('aa') //获取item在items的数组下标,参数squ
 shopCart.updateQuantity(a) //更新商品的数量,参数item
 shopCart.getTotalCount()//获取购物车商品的数量,如果传某个商品的id,那么就返回该商品的数量,参数squ
 </script>

</body>
</html>

下载本文
显示全文
专题