前端學習-第二階段-day05
阿新 • • 發佈:2020-12-21
技術標籤:前端學習日記
練習目標,寫個商品清單,自動計算分類總價,和所有分類總價之和
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
< style>
.all_price {
margin-top: 10px;
border-top: 1px solid #ccc;
width: 280px;
text-align: right;
}
</style>
</head>
<body>
<li>
<button>-</button>
<span>0</span>
< button>+</button>
<span>單價:</span><span>12.5</span><span></span>元 小計:</span>
<em>0</em>
<span>元</span>
</li>
<li>
<button>-</button>
<span>0</span>
< button>+</button>
<span>單價:</span><span>8.5</span><span>元 小計:</span>
<em>0</em>
<span>元</span>
</li>
<li>
<button>-</button>
<span>0</span>
<button>+</button>
<span>單價:</span><span>20</span><span>元 小計:</span>
<em>0</em>
<span>元</span>
</li>
<li>
<button>-</button>
<span>0</span>
<button>+</button>
<span>單價:</span><span>100</span><span>元 小計:</span>
<em>0</em>
<span>元</span>
</li>
<li>
<button>-</button>
<span>0</span>
<button>+</button>
<span>單價:</span><span>518</span><span>元 小計:</span>
<em>0</em>
<span>元</span>
</li>
<li>
<button>-</button>
<span>0</span>
<button>+</button>
<span>單價:</span><span>888</span><span>元 小計:</span>
<em>0</em>
<span>元</span>
</li>
<div class="all_price">總計:0元</div>
<script>
var oLi = document.getElementsByTagName("li");
for (i = 0; i < oLi.length; i++) {
price(oLi[i]);
}
function price(n) {
var all_price = document.getElementsByTagName("div")[0];
var oBtn1 = n.getElementsByTagName("button")[0];
var oBtn2 = n.getElementsByTagName("button")[1];
var oSpan1 = n.getElementsByTagName("span")[0];
var oSpan2 = n.getElementsByTagName("span")[2];
var em = n.getElementsByTagName("em")[0];
var inner = Number(oSpan1.innerHTML);
var unitPrice = Number(oSpan2.innerHTML);
oBtn1.onclick = function () {
inner -= 1;
if (inner < 1) {
inner = 0;
}
oSpan1.innerHTML = inner;
em.innerHTML = inner * unitPrice;
var c = 0;
for (i = 0; i < oLi.length; i++) {
var h = document.getElementsByTagName("li")[i].getElementsByTagName("em")[0].innerHTML;
c += -(-h);
}
all_price.innerHTML = "總計:" + c + "元";
}
oBtn2.onclick = function () {
inner += 1;
oSpan1.innerHTML = inner;
em.innerHTML = inner * unitPrice;
var c = 0;
for (i = 0; i < oLi.length; i++) {
var h = oLi[i].getElementsByTagName("em")[0].innerHTML;
c += -(-h);
}
all_price.innerHTML = "總計:" + c + "元";
}
}
</script>
</body>
</html>