<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style type="text/css">
*{margin:0;padding:0;}
.prod{
width: 200px;
height:300px;
border:1px solid;
/*display: inline-block;*/
padding:10px;
margin: 10px;
float: left;
text-align: center;
}
.btn{
width: 100px;
height:50px;
background:#cc0;
line-height: 50px;
text-align: center;
cursor:pointer;
margin: 0 auto;
margin-bottom: 10px;
}
.buy{
padding: 10px;
margin:10px;
overflow: hidden;
}
</style>
</head>
<body>
<h1>商品列表</h1>
<div class="buy">
</div>
<script src="js/tools.js"></script>
<script>
var products = [
{
"id" : 1,
"title" : "巴朗(BALANG)电脑包 防水书包男旅行包商务休闲双肩包笔记本包15.6英寸",
"img" : "https://img11.360buyimg.com/n4/s160x160_jfs/t12289/317/984430007/272987/221f0836/5a17efa2N9a06a890.jpg",
"price" : 119
},
{
"id" : 2,
"title" : "福临门 东北优质 大米 8kg",
"img" : "https://img10.360buyimg.com/n4/s160x160_jfs/t1960/180/1800461727/128629/6d7d830a/56de26f9N55174aa1.jpg",
"price" : 49.90
},
{
"id" : 3,
"title" : "丝涟 美国(Sealy)高性能泡棉海绵床垫 弹簧床垫 宝宝适用 偏硬珍宝 ",
"img" : "https://img11.360buyimg.com/n4/s160x160_jfs/t14536/252/2707925852/353078/5748b3e4/5ab1d1d4Nff3d2ea4.jpg",
"price" : 1988
},
{
"id" : 4,
"title" : "统一 阿萨姆奶茶500ml*15瓶 整箱",
"img" : "https://img12.360buyimg.com/n4/s160x160_jfs/t11278/30/392755639/112423/3313880b/59eefa1fNa84f0726.jpg",
"price" : 55.90
},
{
"id" : 5,
"title" : "水星(MERCURY)MW325R 300M智能wifi无线路由器增强四天线",
"img" : "https://img10.360buyimg.com/n4/s160x160_jfs/t14839/6/1844178668/107612/b4dfed10/5a5f0c6eN4164626f.jpg",
"price" : 47.50
},
{
"id" : 6,
"title" : "席梦思(Simmons) 独立袋弹簧床垫 双人软床垫 软硬适中 欣喜 1800*2000",
"img" : "https://img10.360buyimg.com/n4/s160x160_jfs/t18169/265/921596746/518509/8d5ad6c4/5ab1ae4eNf860bda5.jpg",
"price" : 7588
},
{
"id" : 7,
"title" : "韩国 东远 金枪鱼罐头 沙拉酱味100g*2罐",
"img" : "https://img13.360buyimg.com/n4/s160x160_jfs/t352/3/2032492851/179277/16ef49e/544dfeb9Nd3e0528f.jpg",
"price" : 15.90
}
];
//遍历渲染页面
var html = "";
products.forEach((prod) => {
html += `<div class="prod">
<div style="display:none">${prod.id}</div>
<div>${prod.title}</div>
<div><img src="${prod.img}"></div>
<div>${prod.price}</div>
<div class="btn">加入购物车</div>
</div>`
});
$(".buy")[0].innerHTML += html;
//点击添加购物车
on($(".buy")[0], "click", (e) => {
e = e || event;
let src = e.target || e.srcElement,
_children = src.parentNode.children,
current = {
id : _children[0].innerText,
title : _children[1].innerText,
img : _children[2].firstChild.src,
price : _children[3].innerText,
amount : 1
}
//reading
let _products = cookie("products");
if(_products)
_products = JSON.parse(_products);
else
_products = [];
for (var i = 0; i < _products.length; i++){
if(_products[i].id == current.id){
_products[i].amount++;
break;
}
}
if(i === _products.length)
_products.push(current);
cookie("products", JSON.stringify(_products),{expires:10,path:"/"});
})
</script>
</body>
</html>