前端学习笔记之购物车
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车</title>
<style>
table,
td,
th {
border: 1px solid #cccccc;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>编号</th>
<th>商品名称</th>
<th>单价</th>
<th>操作</th>
<th>数量</th>
<th>总价</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>保时捷</td>
<td>300</td>
<td>
<input type="button" value="-">
<p>0</p>
<input type="button" value="+">
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>法拉利</td>
<td>400</td>
<td>
<input type="button" value="-">
<p>0</p>
<input type="button" value="+">
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>3</td>
<td>阿斯顿</td>
<td>500</td>
<td>
<input type="button" value="-">
<p>0</p>
<input type="button" value="+">
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>4</td>
<td>法拉利</td>
<td>600</td>
<td>
<input type="button" value="-">
<p>0</p>
<input type="button" value="+">
</td>
<td></td>
<td></td>
</tr>
<tr onmouseover="style.color='red'" onmouseout="style.color='black'">
<td>5</td>
<td>布加迪</td>
<td>700</td>
<td>
<input type="button" value="-">
<p>0</p>
<input type="button" value="+">
</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script>
let tbody = document.querySelector("tbody");
tbody.onclick = function (event) {
if(event.target.nodeName=="INPUT"){
let price = event.target.parentElement.previousElementSibling;
let total_price = event.target.parentElement.nextElementSibling.nextElementSibling;
let count = event.target.parentElement.nextElementSibling;
let number;
if (event.target.value == "+") {
number = event.target.previousElementSibling;
number.innerText++;
count.innerText++;
} else if (event.target.value == "-") {
if (count.innerText > 0) {
number = event.target.nextElementSibling;
number.innerText--;
count.innerText--;
}
}
total_price.innerText=count.innerText*price.innerText;
}
}
</script>
</body>
</html>