- 点击购买页面html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table {
border-collapse: collapse;
}
td {
border: 1px solid;
}
</style>
</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>查看购物车</button>
<script src="js/product.js"></script>
</body>
</html>
2.js点击购买部分
/*
1. 跳转到构物车按钮 - 点击 - 跳转
2. 购买按钮 - 遍历 - 添加点击事件
1》 获取购物车所需要的信息
2》 存储在localStorage中
*/
class Product {
constructor() {
//获取购物车按钮
this.cart_btn = document.querySelector('button');
//获取所有的购买按钮
this.buys = document.querySelectorAll('.buy');
//调用添加事件的方法
this.addEvent();
}
addEvent() {
this.cart_btn.onclick = function () {
location.href = 'cart.html';
}
for (let i = 0, len = this.buys.length; i < len; i++) {
this.buys[i].count = 0;
this.buys[i].onclick = function () {
// 商品ID
let good_id = this.parentNode.parentNode.firstElementChild.firstElementChild.value;
// alert(good_id);
//商品名称
let good_name = this.parentNode.parentNode.firstElementChild.lastChild.nodeValue;
// alert(good_name);
//商品价格
let good_price = this.parentNode.previousElementSibling.innerText;
// alert(good_price);
//商品数量
this.count++;
/*
key : value
key 'product_' + good_id
value : '{"id" : 1,"name" : "水杯","price" : "39","num" : 3}'
`{"id" : ${good_id},"name" : "${good_name}","price" : "${good.price}","num" : ${this.count}}`
*/
//本地存储
window.localStorage.setItem(`product_${good_id}`, `{"id" : ${good_id},"name" : "${good_name}","price" : "${good_price}","num" : ${this.count}}`);
}
}
}
}
new Product();
3.购买显示页面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 src="js/cart.js"></script>
</body>
</html>
4.购买显示页面js部分
/*
//1. 拿回localStorage中的数据--过滤出自己的商品
//2. 动态添加到页面中
*/
class Cart{
constructor(){
this.tab = document.querySelector('#tab');
this.init();
}
init() {
let storage = window.localStorage;
for(let i = 0;i < storage.length;i ++){
let key = storage.key(i);
if(key.startsWith('product_')){
let good = JSON.parse(storage.getItem(key));
//在表格中插入一行
let _tr = this.tab.insertRow();
//在行中插入td
let _td = _tr.insertCell();
_td.innerText = good.id;
_td = _tr.insertCell();
_td.innerText = good.name;
_td = _tr.insertCell();
_td.innerText = good.price;
_td = _tr.insertCell();
_td.innerText = good.num;
}
}
}
}
new Cart();