需求
使用JS实现购物车功能02

具体代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车02</title>
</head>
<body>
<table align="center" border="2" id = "shop">
<tr>
<th colspan="4" align="center">商品列表<input id="add" type="button" value="一键上架"></th>
</tr>
<tr>
<th>商品序号</th>
<th>商品名称</th>
<th>出售价格</th>
<th>操作</th>
</tr>
</table>
<br>
<br>
<br>
<br>
<br>
<table align="center" border="2" id = "cart">
<tr>
<th colspan="4" align="center">购物车<input id="clear" type="button" value="一键清空"></th>
</tr>
<tr>
<th>商品名称</th>
<th>商品价格</th>
<th>商品数量</th>
<th>操作</th>
</tr>
</table> <h3 id="total" align="center">总价: ¥0.0</h3> <script type="text/javascript">
var goods_name = ["阿尔卑斯棒棒糖","耳机","北京糖葫芦","智能扫地机器人"];
var goods_price = ["1.5","30","5","258"];
//一键上架
var add = document.getElementById("add");
add.onclick = function(){
var shop = document.getElementById("shop");
for(var i = 0; i< goods_name.length;i++){
var row = shop.insertRow();
row.insertCell().innerHTML = i + 1;
row.insertCell().innerHTML = goods_name[i];
row.insertCell().innerHTML = "¥" + goods_price[i];
row.insertCell().innerHTML = "<button id='" + i + "' onclick='addCart(this);'>加入购物车</button>";
}
this.setAttribute("disabled", true);
} var cartData = { } var index = 0;
//准备加入购物车的数据
function addCart(btn) { var gname = goods_name[btn.id];
var gobj = cartData[gname]; if(!gobj){//没有数据
//新增一条数据
cartData[goods_name[btn.id]] = {
id:btn.id,
count:1,
index:index++
}
}else{
cartData[goods_name[btn.id]].count++;
}
//console.log(cartData);
showCart(cartData);
}
//加入购物车
function showCart(obj){
clearCart();
getTotal(obj);
var cart = document.getElementById("cart");
for(var k in obj){
var row = cart.insertRow();
row.insertCell().innerHTML = k;
row.insertCell().innerHTML = "¥" + goods_price[obj[k].id];
row.insertCell().innerHTML = obj[k].count;
row.insertCell().innerHTML = "<button id='" + k + "' onclick='deleteRow(this);'>删除</button>";
}
}
//清空购物车
var clear = document.getElementById("clear");
clear.onclick = function(){
clearCart();
cartData = {};
}
//清空购物车的方法
function clearCart(){
var cart = document.getElementById("cart");
var rows = cart.rows;
for(var i = rows.length - 1 ; i > 1 ; i--){
cart.deleteRow(i);
}
total = 0.0;
//更新总价
document.getElementById("total").innerHTML = "总价:¥" + total;
} var total = 0.0;
//得到总价
function getTotal(obj){ for(var k in obj){
var subTotal = goods_price[obj[k].id] * obj[k].count;
total += subTotal;
}
//更新总价
document.getElementById("total").innerHTML = "总价:¥" + total; } //删除整行
function deleteRow(btn){
var cart = document.getElementById("cart");
var rowIndex = btn.parentNode.parentNode.rowIndex;
cart.deleteRow(rowIndex);
delete cartData[btn.id];
total = 0.0;
getTotal(cartData);
} </script>
</body>
</html>

效果图
样式比较丑,不要介意哈

JS实现购物车02-LMLPHP

05-04 12:54