做的购物车比较简单,点击商品列表后面的购买按钮,最后点击查看购物车按钮,可以在购物车页面查看序号、商品名称、商品单价,以及根据点击某件商品的次数来算出商品的数量,主要是通过获取cookie来获取数据。
实现代码以及相应注释如下:
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<style>
table{border-collapse:collapse;}
td{border:1px solid;}
</style>
<script>
window.onload = function(){
var oA = document.getElementsByTagName('a');
var date = new Date();
date.setDate(date.getDate()+1);
for(var i = 0;i<oA.length;i++){
oA[i].num = 0;
oA[i].onclick = function(){
this.num ++;
var id= this.parentNode.parentNode.firstChild.firstChild.value;
var name = this.parentNode.parentNode.firstChild.lastChild.nodeValue;
//alert(name);
var price = this.parentNode.previousSibling.innerHTML;
var cookieValue="{id:" + id + ",name:'" + name + "',price:" + price + ",num:" + this.num + "}";
var cookieName = "product_" + id;
document.cookie = cookieName+'='+cookieValue+";expires="+date;
//alert(document.cookie);
}
}
};
</script>
</head>
<body>
<table>
<tr>
<td>商品名</td><td>价格</td><td>操作</td>
</tr>
<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 οnclick="window.location='car.html';">查看购物车</button>
</body>
</html>
car.html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<style>
table{border-collapse:collapse;}
td{border:1px solid;}
</style>
<script>
window.onload = function(){
//alert(document.cookie);
var arr = document.cookie.split('; ');
var index = 1;
for(var i = 0;i<arr.length;i++){
//arr[i]为name=value的cookie
//以=号分割,val数组中第一个元素为cookie 名字 第二个元素为 cookie值
var val = arr[i].split('=');
if(val[0].indexOf('product_') == 0){
//cookie名以product_开头,说明是添加到购物车中的商品信息
//还原商品的json对象
var product = eval('('+val[1]+')');
//在表格中插入行
var _tr = document.getElementById("tab").insertRow();
var _td = _tr.insertCell(); //序号
_td.innerHTML = index++;
_td = _tr.insertCell(); //商品名称
_td.innerHTML = product.name;
_td = _tr.insertCell();//单价
_td.innerHTML = product.price;
_td = _tr.insertCell();//数量
_td.innerHTML = product.num;
}
}
};
</script>
</head>
<body>
<table id="tab">
<tr><td>序号</td><td>商品名称</td><td>商品单价</td><td>数量</td></tr>
</table>
</body>
</html>