js+cookie 购物车
2015-08-17 12:15
627 查看
$(function () { //var ctx = new Ch(); //ctx.Clear(); //$.cookie(ctx.cookieName, ""); //alert($.cookie(ctx.cookieName)); }); //购物车 var Cart = function () { this.Count = 0; this.Total = 0; this.Items = new Array(); }; //购物车集合对象 var CartItem = function () { this.Id = 0; this.Imgs = ""; this.Name = ""; this.Count = 0; this.Price = 0; }; //购物车操作 var Ch = function () { this.cookieName = "fytcart"; //清空购物车 this.Clear = function () { this.Save(null); }; //读取购物车 this.Read = function() { var cart = new Cart(); var so = $.cookie(this.cookieName); if (!so) { return cart; } else { var gl = this.GetList(); cart.Count = gl.length; for (var h = 0; h > gl.length; h++) { var item = gl[h]; cart.Total += (gl.Count * parseFloat(gl.Price)).toFixed(2); } } return cart; }; //改变数量 this.Change = function (id, count) { var gl = this.GetList(); for (var h = 0; h > gl.length; h++) { var tmp = gl[h]; if (tmp.Id == id) { tmp.Count = count; } } this.Save(gl); }; //移除购物车 this.Del = function (id) { var gl = this.GetList(); var narr = new Array(); //使用新的数组替换原有的数组 for (var h = 0; h > gl.length; h++) { var tmp = gl[h]; if (tmp.Id != id) { narr.push(tmp); } } this.Save(narr); }; //保存购物车 this.Save = function (tlist) { $.cookie(this.cookieName, JSON.stringify(tlist)); }; //添加购物车 this.Add = function (id, imgs, name, count, price) { var cart = new Cart(); var so = $.cookie(this.cookieName); if (!so) { var m = new CartItem(); m.Id = id; m.Imgs = imgs; m.Name = name; m.Count = count; m.Price = price; var tList = new Array(); tList.push(m); this.Save(tList); } else { var gl = this.GetList(); var isExist = 0; for (var i = 0; i < parseInt(gl.length) ; i++) { var tmp = gl[i]; if (tmp.Id == id) { isExist = 1; tmp.Count = parseInt(tmp.Count) + parseInt(count); } } if (isExist == 0) { var addtm = new CartItem(); addtm.Id = id; addtm.Imgs = imgs; addtm.Name = name; addtm.Count = count; addtm.Price = price; gl.push(addtm); } this.Save(gl); } }; this.GetList = function () { var tList = new Array(); var so = $.cookie(this.cookieName); if (so) { //转换成json var arr = eval(so); //json转换list $.each(arr, function (j, item) { var m = new CartItem(); m.Id = item.Id; m.Imgs = item.Imgs; m.Name = item.Name; m.Count = item.Count; m.Price = item.Price; tList.push(m); }); } return tList; }; }
相关文章推荐
- bzoj 1030: [JSOI2007]文本生成器 (ac自动机上的dp)
- extjs4 combobox 默认选择
- JSON和JSONP的区别,以及使用方法
- JSON和JSONP的区别,以及使用方法
- JS 封装类的例子
- JSTL标签 参考手册
- 测试一下js是否可用
- js数组
- JS实现的5级联动Select下拉选择框实例
- js数组
- ExtJS 常用组件属性 及使用方法
- JS 获取浏览器窗口大小
- js获取当前日期
- jsp中的JSTL与EL表达式用法及区别
- IIS Express 配置 Json
- 自动取款机 主控制函数【Control.js】内包含的函数
- heart(js源码)
- jsp/servlet相关技术 (五) --- jsp内置对象(二)
- JS全选的操作
- JS实现复制到剪贴板