add方法,传入一个参数items。items是一个数组,数组元素为{name:String,price:Number}。通过add方法可以在在购物车列表新增商品
bind方法,实现点击删除,能够删除对应的列
同时,注意总计的商品总价应该符合逻辑计算,所有价钱应该保留小数点后2位。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<table id="jsTrolley">
<thead><tr><th>名称</th><th>价格</th><th>操作</th></tr></thead>
<tbody>
<tr><td>产品1</td><td>10.00</td><td><a href="javascript:void(0);">删除</a></td></tr>
<tr><td>产品2</td><td>30.20</td><td><a href="javascript:void(0);">删除</a></td></tr>
<tr><td>产品3</td><td>20.50</td><td><a href="javascript:void(0);">删除</a></td></tr>
</tbody>
<tfoot><tr><th>总计</th><td colspan="2">60.70(3件商品)</td></tr></tfoot>
</table>
</body>
<script type="text/javascript">
function add(items) {
var sum = 0,
num = 0,
html = "",
table = document.getElementById("jsTrolley"),
tbody = table.getElementsByTagName("tbody")[0],
tfoot = table.getElementsByTagName('tfoot')[0],
tr = tbody.getElementsByTagName("tr");
price = tfoot.getElementsByTagName('td')[0];
for (var i = 0; i < tr.length; i++) {
var a = tr[i].getElementsByTagName('td')[1];
sum += parseFloat(a.innerHTML);
}
for(var i =0;i<items.length;i++){
sum += items[i].price;
html += "<tr><td>"+items[i].name+"</td><td>"+items[i].price.toFixed(2)+"</td><td><a href='javascript:void(0);'>删除</a></td></tr>";
}
html = tbody.innerHTML+html;
tbody.innerHTML = html;
num = tbody.getElementsByTagName("tr").length;
price.innerHTML = sum.toFixed(2)+"("+num+"件商品)";
}
add([{name:"dd",price:11.00},{name:"ddd",price:55.0}]);
function bind() {
function fn(){
var node = this.parentNode.parentNode;
node.parentNode.removeChild(node);
var sum = 0,num=0;
var tbody = document.getElementById("jsTrolley").getElementsByTagName("tbody")[0];
var tr = tbody.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
var a = tr[i].getElementsByTagName('td')[1];
sum += parseFloat(a.innerHTML);
num++;
}
num = tbody.getElementsByTagName("tr").length;
price.innerHTML = sum.toFixed(2)+"("+num+"件商品)";
}
var del = document.getElementById("jsTrolley").getElementsByTagName("a");
for (var i = 0; i < del.length; i++) {
del[i].onclick = fn;
}
}
bind();
</script>
</html>