setCookie


<h2>购物车页面</h2>

<table class="table table-bordered">
<thead>
<tr>
<td>商品名称</td>
<td>商品价格</td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>

<script>
//cookie加载购物车
function load() {
//获取值,此时为字符串类型
var liststr = getCookie("shopcar");
//类型转换
var list = JSON.parse(liststr);
$("#tb").empty();
$(list).each(function () {
$("#tb").append(
'<tr>' +
'<td>' + this.Name + '</td>' +
'<td>' + this.Price + '</td>' +
'</tr>'
)
})
}
load();

//取值
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;
}
};
//存值
function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //匹配字段
if (arr = document.cookie.match(reg)) {
return unescape(arr[2]);
} else {
return null;
}
};
</script>

原文地址:https://www.cnblogs.com/CoreColor/p/13448880.html