商品详细:
//cookie零时存购物车
function addcar() {
//判断cookie是否有值
if (getCookie("shopcar") == null) {
//数组类型
setCookie("shopcar", "[]");
} //这里举例子,值写死
var obj = {
Name: "球鞋",
Price: "1200"
};
//获取值,此时为字符串类型
var liststr = getCookie('shopcar');
//类型转换
var list = JSON.parse(liststr);
//追加值
list.push(obj);
//保存到cookie中
setCookie("shopcar", JSON.stringify(list));
location.href = "/Default/ShopCar";
}
购物车:
//cookie加载购物车
function load() {
//获取值,此时为字符串类型
var liststr = getCookie("shopcar");
//类型转换
var list = JSON.parse(liststr);
$("#tb").empty();
$(list).each(function () {
$("#tb").append(
'' +
'' + this.Name + '' +
'' + this.Price + '' +
''
)
})
}
load();
JavaScript:
/**
* cookie中存值
* */
function setCookie(name, value) {
if (value) {
var days = 1; //定义一天
var exp = new Date();
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
// 写入Cookie, toGMTString将时间转换成字符串
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString;
}
};
/**
* cookie中取值
* */
function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //匹配字段
if (arr = document.cookie.match(reg)) {
return unescape(arr[2]);
} else {
return null;
}
};
(责任编辑:范老师)