本文實例講述了jQuery基于cookie實現的購物車。分享給大家供大家參考,具體如下:
這里分析了jquery購物車原理,包括添加商品及數量到購物車 cookie 中,判斷購物車中有無商品,如果有,則把json字符串轉換成對象,返回當前商品在 cookie 中的總數。
將商品放入購物車:
$(function(){$(".tc").hide();var PId = $("#hfPId").val(); // 商品的IDvar 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 cookieoptions = 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程序設計有所幫助。