使用Vue框架
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<form action="bbb">
<h2 align="center">购物车</h2>
<table border="1" width="100%">
<thead align="center">
<th><input type="checkbox" v-model="checkedAll" @click="gouxuan()">全选</th>
<th>编号</th>
<th>名称</th>
<th>图片</th>
<th>数量</th>
<th>价格</th>
<th>移除</th>
</thead>
<tbody align="center">
<tr v-for="(p,i) in list">
<td><input type="checkbox" :checked="p.c"></td>
<td>{{i+1}}</td>
<td>{{p.name}}</td>
<td><img width="100" :src="p.img"></td>
<td>
<input type="button" value="-" @click="jian(i)">
<input type="number" :value="p.count">
<input type="button" value="+" @click="jia(i)">
</td>
<td>{{p.price}}</td>
<td><input type="button" value="移除" @click="remove(i)"></td>
</tr>
</tbody>
<tfoot align="center">
<tr>
<td colspan="4">总价格</td>
<td>{{total}}</td>
<td colspan="2">
<input type="submit" value="立即结算">
</td>
</tr>
</tfoot>
</table>
<br/><br/><br/><br/><br/>
<h2 align="center">物品列表</h2>
<table border="1" width="100%">
<thead align="center">
<tr>
<th>名称</th>
<th>图片</th>
<th>价格</th>
<th>是否购买</th>
</tr>
</thead>
<tbody align="center">
<tr v-for="(p,i) in products">
<td>{{p.name}}</td>
<td><img :src="p.img" width="100"> </td>
<td>{{p.price}}</td>
<td><input type="button" value="加入购物车" @click="add(i)"></td>
</tr>
</tbody>
</table>
</form>
</div>
<script>
var vue=new Vue({
el:"#app",
data:{
checkedAll:true,
list:[
{name:"商品1",img:"1.jpg",price:200.00,count:1,c:true}
],
products:[
{name:"商品1",img:"1.jpg",price:200.00},
{name:"商品2",img:"2.jpg",price:300.00},
{name:"商品3",img:"3.jpg",price:400.00},
{name:"商品4",img:"4.jpg",price:500.00}
],
total:0.00
},
methods: {
add:function(i){
var find=false;
for (var x=0;x<this.list.length;x++) {
if (this.list[x].name == this.products[i].name) {
this.jia(x);
find = true;
break;
}
}
if (!find) {
this.list.push({name: this.products[i].name, price:this.products[i].price, img: this.products[i].img, count: 1, c: true});
this.sum();
}
},
remove: function (i) {
this.list.splice(i,1);
this.sum();
},
jia: function (i) {
this.list[i].count++;
this.sum();
},
jian: function (i) {
if (this.list[i].count>1){
this.list[i].count--;
}
this.sum();
},
gouxuan: function () {
for (var i=0; i<this.list.length;i++){
this.list[i].c=!this.checkAll;
}
},
sum:function () {
this.total=0.00;
for (var i=0; i<this.list.length;i++){
this.total+=this.list[i].price*this.list[i].count;
}
}
},
mounted:function () {
this.sum();
}
});
</script>
</body>
</html>