这篇文章主要介绍了 jQuery 基于 cookie 实现购物车的方法, 结合实例形式简单分析了 jQuery 基于 cookie 实现针对商品信息的购物车存储功能, 具有一定参考借鉴价值, 需要的朋友可以参考下
jQuery 是一个兼容多浏览器的 javascript 框架,核心理念是 write less,do more(写得更少, 做得更多)。jQuery 在 2006 年 1 月由美国人 John Resig 在纽约的 barcamp 发布,吸引了来自世界各地的众多 JavaScript 高手加入,由 Dave Methvin 率领团队进行开发。
本文实例讲述了 jQuery 基于 cookie 实现的购物车。分享给大家供大家参考,具体如下:
这里分析了 jquery 购物车原理,包括添加商品及数量到购物车 cookie 中,判断购物车中有无商品,如果有,则把 json 字符串转换成对象,返回当前商品在 cookie 中的总数。
将商品放入购物车:
- $(function(){
- $(".tc").hide();
- var PId = $("#hfPId").val(); // 商品的ID
- var PName = $("#lblPName").text(); // 商品名称
- var PMemberPrice = $("#lblPMemberPrice").text(); // 会员价
- var PAmount = 1;
- var jsonStr = "[{'PId':'" + PId + "','PName':'" + PName + "','PMemberPrice':'" + PMemberPrice + "','PAmount':'" + PAmount + "'}]";
- //将商品放入购物车
- $("#putCart").click(function(){
- setCookie(PId, jsonStr);
- });
赋值:
- var setCookie = function(name, value, options){
- if (typeof value != 'undefined') { // name and value given, set cookie
- options = options || {};
- if (value === null) {
- value = '';
- options.expires = -1;
- }
- var expires = '';
- if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
- var date;
- if (typeof options.expires == 'number') {
- date = new Date();
- date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
- } else {
- date = options.expires;
- }
- expires = '; expires=' + date.toUTCString();
- }
- var path = options.path ? '; path=' + (options.path) : '';
- var domain = options.domain ? '; domain=' + (options.domain) : '';
- var secure = options.secure ? '; secure' : '';
希望本文所述对大家 jQuery 程序设计有所帮助。
来源: http://www.phperz.com/article/17/0227/267926.html