简易购物车原理
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<style>
table{border-collapse:collapse;}
td{border:1px solid;}
</style>
</head>
<body>
<table>
<tr>
<td>商品名</td><td>价格</td><td>操作</td>
</tr>
注意以为js使用原生,tr td 格式不能 有空格,
<tr><td><input type="hidden" value="1">水杯</td><td>29</td><td><a class="buy" href="javascript:;">购买</a></td></tr>
<tr><td><input type="hidden" value="2">电脑</td><td>4999</td><td><a class="buy" href="javascript:;">购买</a></td></tr>
<tr><td><input type="hidden" value="3">手机</td><td>1999</td><td><a class="buy" href="javascript:;">购买</a></td></tr>
</table>
<button id="btn">查看购物车</button>
<script type="text/javascript">
//获取跳转到购物车的按钮
var oToCart = document.getElementById("btn");
oToCart.onclick = function(){
// 跳转到cart.html购物车页面
window.location = 'cart.html';
}
//获取所有的购买按钮
var oA = document.getElementsByTagName('a');
for(var i = 0,len = oA.length;i < len;i ++){
oA[i].num = 0;
oA[i].onclick = function(){
//商品ID
var id = this.parentNode.parentNode.firstChild.firstChild.value;
//商品名称
var name = this.parentNode.parentNode.firstChild.lastChild.nodeValue;
//商品价格
var price = this.parentNode.previousSibling.innerHTML;
//商品数量
this.num ++;
//'{"id":1,"name":"水杯","price":1999,"num":2}'
// JSON.parse() JSON.stringify()
//'{"id":' + id + ',"name":"' + name + '","price":' + price + ',"num":' + this.num + '}'
var date = new Date();
date.setDate(date.getDate() + 7);
//创建cookie
document.cookie = 'product_' + id + '=' + '{"id":' + id + ',"name":"' + name + '","price":' + price + ',"num":' + this.num + '}' + ';expires=' + date + ';path=/';
}
}
</script>
</body>
</html>
下面是购物车页:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<style>
table{border-collapse:collapse;}
td{border:1px solid;}
</style>
</head>
<body>
<table id="tab">
<tr><td>序号</td><td>商品名称</td><td>商品单价</td><td>数量</td></tr>
</table>
<script type="text/javascript">
// 查看cookie
alert(document.cookie);
// 将cookie字符串截取成数组
var arr = document.cookie.split('; ');
// 获取表格
var oTable = document.getElementById("tab");
for(var i = 0,len = arr.length;i < len ;i ++){
var list = arr[i].split('=');
// 判断有误此商品
if(list[0].indexOf('product_') != -1){
//将字符串转成对象
var json = JSON.parse(list[1]);
//在表格中插入一行
var _tr = oTable.insertRow();
var _td = _tr.insertCell(); //在行内插入一个单元格
_td.innerHTML = json.id;
_td = _tr.insertCell();
_td.innerHTML = json.name;
_td = _tr.insertCell();
_td.innerHTML = json.price;
_td = _tr.insertCell();
_td.innerHTML = json.num;
}
}
</script>
</body>
</html>