js加减运算·传参

时间:2022-04-07 18:40:54

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title></title>
<style>
body {
font-family: "微软雅黑";
}

em {
font-style: normal;
}

ul li {
list-style: none;
margin-bottom: 5px;
}
</style>
</head>

<body>
<ul id="list">
<li>
<input type="button" value="-" />
<strong>0</strong>
<input type="button" value="+" /> 单价:
<em>8.5元</em> 小计:
<span>0元</span>
</li>

<li>
<input type="button" value="-"/>
<strong>0</strong>
<input type="button" value="+"/> 单价:
<em>8.5元</em> 小计:
<span>0元</span>
</li>

<li>
<input type="button" value="-"/>
<strong>0</strong>
<input type="button" value="+"/> 单价:
<em>8.5元</em> 小计:
<span>0元</span>
</li>

<li>
<input type="button" value="-"/>
<strong>0</strong>
<input type="button" value="+"/> 单价:
<em>8.5元</em> 小计:
<span>0元</span>
</li>
</ul>

<script>
/*
利用传参方式,完成购物车的加减
1.尽量相同的HTML结构
2.尽量通过父元素寻找元素

* */
var oList = document.getElementById("list")
var aLi = oList.getElementsByTagName("li")
for (var i=0;i<aLi.length;i++) {
tab(aLi[i])
}

function tab(obj){
var oInput = obj.getElementsByTagName("input")
var oStr = obj.getElementsByTagName("strong")[0]
var oSpan = obj.getElementsByTagName("span")[0]
var num = 0
//          console.log(oInput[1])
oInput[1].onclick = function() {
num++
//           console.log(num)
oStr.innerHTML = num
oSpan.innerHTML = 8.5 * num + "元"
}

oInput[0].onclick = function() {
num--
//           console.log(num)
if(num<0){
num=0
}
oStr.innerHTML = num
oSpan.innerHTML = 8.5 * num + "元"
}
}


</script>

</body>

</html>