<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车案例</title>
<style>
table,th,td{
border: 1px solid black;
border-collapse: collapse;
}
tr td{
text-align: center;
font-weight: bold;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
</tr>
</thead>
<tbody>
<tr>
<th>iphone6</th>
<th>¥4488.00</th>
<th>
<button>-</button>
<span>1</span>
<button>+</button>
</th>
<th>¥4488.00</th>
</tr>
<tr>
<th>iphone6 plus</th>
<th>¥5288.00</th>
<th>
<button>-</button>
<span>7</span>
<button>+</button>
</th>
<th>¥37016.00</th>
</tr>
<tr>
<th>iphone6</th>
<th>¥4288.00</th>
<th>
<button>-</button>
<span>5</span>
<button>+</button>
</th>
<th>¥21440.00</th>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">Total:</td>
<td>¥</td>
</tr>
</tfoot>
</table>
<script>
var buttons = document.getElementsByTagName('button');
var totalEle = document.getElementsByTagName('tfoot')[0].children[0].children[1];
var tbody_trs = document.getElementsByTagName('tbody')[0].children;
var sumEles = new Array(tbody_trs.length); //每一个商品的小计价格
var totalcount =0; //商品总价
for(var i=0;i<tbody_trs.length;i++)
{
sumEles[i] = tbody_trs[i].lastElementChild;
totalcount = totalcount +parseInt((sumEles[i].innerHTML).slice(1));
}
totalEle.innerHTML = '¥' + totalcount.toFixed(2);
console.log(totalEle.innerHTML);
for(var i=0;i<buttons.length;i++)
{
buttons[i].onclick = function(){
var text = this.parentElement.children[1];
var n = text.innerHTML;
var singlePrice = this.parentElement.previousElementSibling.innerHTML;
singlePrice = singlePrice.slice(1);
if(this.innerHTML == '+'){
n++;
totalcount += parseInt(singlePrice);
}
else{
if(text.innerHTML != '0'){
n--;
totalcount -= parseInt(singlePrice);
}
}
text.innerHTML = n;
var sumEle = this.parentElement.nextElementSibling;
sumEle.innerHTML = '¥'+(singlePrice*n).toFixed(2);
totalEle.innerHTML = '¥' + totalcount.toFixed(2);
}
}
</script>
</body>
</html>
DOM元素查询与修改——购物车案例
最新推荐文章于 2022-05-31 17:17:07 发布