js实现购物车价格计算效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
button{
width: 40px;
font-size: 20px;
}
#num{
font-style: normal;
font-size: 20px;
padding: 0 5px;
}
</style>
<script type="text/javascript">
window.onload = function(){
var btns = document.getElementsByTagName('button');
var num = document.getElementById('num');
var unit = document.getElementById('unit');
var total = document.getElementById('total');
// console.log(btns,num,total);
var nums = Number(num.innerHTML);
var units = Number(unit.innerHTML);
var sum = 0;
console.log(typeof units,units);
for(var i = 0; i < btns.length; i++){
btns[i].index = i;
btns[i].onclick = function(){
if(this.index == 0){
if(nums === 0){
nums = 0;
// sum = nums * units;
}else{
nums--;
// sum = nums * units;
}
}else if(this.index == 1){
nums++;
}
sum = nums * units;
num.innerHTML = nums;
total.innerHTML = sum;
}
}
}
</script>
</head>
<body>
<div class="wrap">
<button type="button">-</button>
<i id="num">0</i>
<button type="button">+</button>
单价:<spam id="unit">12.5</spam>元
总价:<span id="total">0</span>元
</div>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634831.html