<body>
<div class="wrap">
<table>
<tr>
<td>商品</td>
<td>单价</td>
<td>数量</td>
<td>小计</td>
</tr>
<tr>
<td>
<img src="images/shop2.jpg" alt='#' width="220" height="220">
</td>
<td class='nor-pri'>8</td>
<td>
<p>
<span class="lower">-</span>
<span class="val">0</span>
<span class="add">+</span>
</p>
</td>
<td class="price">0</td>
</tr>
<tr>
<td>
<img src="images/shop1.jpg" alt='#' width="220" height="220">
</td>
<td class='nor-pri'>10</td>
<td>
<p>
<span class="lower">-</span>
<span class="val">0</span>
<span class="add">+</span>
</p>
</td>
<td class="price">0</td>
</tr>
<tr>
<td>
<img src="images/shop2.jpg" alt='#' width="220" height="220">
</td>
<td class='nor-pri'>12.5</td>
<td>
<p>
<span class="lower">-</span>
<span class="val">0</span>
<span class="add">+</span>
</p>
</td>
<td class="price">0</td>
</tr>
<tr>
<td>
<img src="images/shop3.jpg" alt='#' width="220" height="220">
</td>
<td class='nor-pri'>23</td>
<td>
<p>
<span class="lower">-</span>
<span class="val">0</span>
<span class="add">+</span>
</p>
</td>
<td class="price">0</td>
</tr>
</table>
<div class="total">
<span>已选中商品件数:<b>0</b>件</span>
<span>总价格:<b>0</b></span>
</div>
</div>
<script>
var aWrap = document.getElementsByClassName( 'wrap' )[0],
aLower = aWrap.getElementsByClassName( 'lower' ),
aVal = aWrap.getElementsByClassName( 'val' ),
aAdd = aWrap.getElementsByClassName( 'add' ),
aB = aWrap.getElementsByTagName( 'b' ),
aPrice = aWrap.getElementsByClassName( 'price' ),
aNorpri = aWrap.getElementsByClassName( 'nor-pri' ),
length = aLower.length,
arrNum = [],
arrPic = [];
for (var i = 0; i <length; i++) {
//获取初始值
arrNum[i] = aVal[i].innerText - 0; //-0把aVal[i].innerText转成Number类型
arrPic[i] = aNorpri[i].innerText - 0;//同上
//加加
aAdd[i].bool = true;//给aAdd每个加上一个bool = true
aAdd[i].index = i;
aAdd[i].onclick = event
//减减
aLower[i].index = i;
// aLower[i].bool = false;
aLower[i].onclick = event;
}
function event(){
var tInd = this.index;
if( this.bool ){ //我们给每个加加 加上bool = true 没有给减减加 点减减的时候this.bool是undefined 是为假;走 else
arrNum[tInd] ++ ;
} else {
arrNum[tInd] --;
// if( arrNum[tInd] < 0 ) arrNum[tInd] = 0;
arrNum[tInd] = Math.max( 0 , arrNum[tInd] );//取0和arrNum的最大值 arrNum[tInd] 0 1 2 .... 当等于0的时候 最大就是0; arrNum[tInd]小于0还是取0;
}
//封装函数
function change( a ){
var numSum = 0,
totPic = 0;
for ( i = 0; i <length; i++) {
numSum += arrNum[i];
totPic += arrNum[i] * arrPic[i];
}
aVal[a].innerText = arrNum[a];
aPrice[a].innerText = arrNum[a] * arrPic[a];
aB[0].innerText = numSum;
aB[1].innerText = totPic;
}
</script>
</body>
重点:
arrNum[ tInd ] = Math.max( 0 , arrNum[tInd] );//取0和arrNum的最大值 arrNum[tInd] 0 1 2 .... 当等于0的时候 最大就是0; arrNum[tInd]小于0还是取0;