1. 程式人生 > >商品加減,總計

商品加減,總計

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul id="list">
    <li>
        <input type="button" value="-"/>
        <strong>0</strong>
        <input type="button" value="+"/>
        單價:<em>12.5元</em>
        小計:<span>0元</span>
    </li>
    <li>
        <input type="button" value="-"/>
        <strong>0</strong>
        <input type="button" value="+"/>
        單價:<em>10.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元</em>
        小計:<span>0元</span>
    </li>
    <li>
        <input type="button" value="-"/>
        <strong>0</strong>
        <input type="button" value="+"/>
        單價:<em>14.5元</em>
        小計:<span>0元</span>
    </li>
</ul>
<p>
    商品合計共:<span id="all">0</span>件,共花費了:<span id="money">0</span>元<br/>
</p>
</body>
<script>
    window.onload=function () {
        var oIpt=document.getElementsByTagName('input');
        var oSpan=list.getElementsByTagName('span');
        var allNum=0;

        for(var i=0;i<oIpt.length;i++){
            oIpt[i].onclick=function(){
                //點選增加減少
                if(this.value=='+'){
                   var Num=this.parentNode.children[1].innerHTML;
                   Num++;
                   allNum++;
                   this.parentNode.children[1].innerHTML=Num;
                }else{
                    var Num=this.parentNode.children[1].innerHTML;
                    Num--;
                    if(Num<0){
                        this.parentNode.children[1].innerHTML=0;
                    }else{
                        this.parentNode.children[1].innerHTML=Num;
                        allNum--;
                    }
                }
                Num=this.parentNode.children[1].innerHTML; //獲取數量
                var Pri=this.parentNode.children[3].innerHTML.replace('元',''); //獲取單價
                var Tol=this.parentNode.children[4].innerHTML.replace('元',''); //獲取原總價
                Tol=Num*Pri; //計算總價
                this.parentNode.children[4].innerHTML=Tol+'元'; //賦值給總價
                all.innerHTML=allNum;  //計算商品總件數
                //計算總商品總價格
                var allMoney=0;
                for(var i=0;i<oSpan.length;i++){
                    Sum=Number(oSpan[i].innerHTML.replace('元',''));
                    allMoney+=Sum;
                }
                money.innerHTML=allMoney;
            }
        }
    }
</script>
</html>