1、html代码部分
<h1 align="center">你好,书城</h1>
<hr/>
<div class="box"></div>
<hr/>
<div class="shopCar"></div>
2、css样式部分
* {
margin: 0;
padding: 0;
}
.shopCar {
width: 88%;
margin: 20px auto;
border: 5px solid skyblue;
background-color: orange;
border-radius: 20px;
padding: 20px;
}
.book {
width: 25%;
display: inline-block;
text-align: center;
padding: 20px 0;
}
3、js部分:
(1)获取页面元素
var box=document.querySelector(".box");
var shopCar=document.querySelector(".shopCar");
(2) 准备数据:
var dataStr = '{' +'"img":["d1.jpg","d2.jpg","d3.jpg","d4.jpg","d5.jpg","d6.jpg","d7.jpg","d8.jpg"],' +
'"name":[' +
'"仍然",' +
'"此刻花开(一本精美绝伦的手工纸雕书)",' +
'"进击的局座:悄悄话(独家附赠精美小册子)",' +
'"股票短线交易的24堂精品课(第二版)",' +
'"锦绣旗袍 (全二册)",' +
'"大暴雪",' +
'"男孩的冒险书(少儿绘图版,全三册)",' +
'"古龙作品集套装72册(大陆正版合法授权)"],' +
'"author":[' +
'"庆山",' +
'"徐静",' +
'"徐静",' +
'"徐静",' +
'"徐静",' +
'"徐静",' +
'"徐静",' +
'"徐静"], ' +
'"newprice":["63.60","33.30","12","15","20","3","8","0.6"],' +
'"oldprice":["660","330","120","105","200","30","80","6000"]' +
'}';
(3) 解析数据;
var data=JSON.parse(dataStr);
console.log(data);
(4)填充数据,将所有的数据填充到box内:
for(var i=0;i<data.img.length;i++){
var div=document.createElement("div");
div.className="book";
//添加图片
var img=document.createElement("img");
img.src="img/"+data.img[i];
div.appendChild(img);
//添加书名
var p_bookname=document.createElement("p");
p_bookname.innerHTML=data.name[i];
div.appendChild(p_bookname);
//添加作者
var p_author=document.createElement("p");
p_author.innerHTML=data.author[i];
div.appendChild(p_author);
//添加价格
var p_price=document.createElement("p");
//新价格
var nSpan=document.createElement("span");
nSpan.innerHTML="¥"+data.newprice[i];
p_price.appendChild(nSpan);
//旧价格
var oSpan=document.createElement("del");
oSpan.innerHTML="¥"+data.oldprice[i];
p_price.appendChild(oSpan);
div.appendChild(p_price);
//添加按钮
var button=document.createElement("button");
button.innerHTML="添加到购物车";
button.onclick=function(){
//获取整个div
var node=this.parentNode;
var result=node.cloneNode(true);
result.removeChild(result.childNodes[4]);
shopCar.appendChild(result);
};
div.appendChild(button);
box.appendChild(div);
};
4、部分效果图: