JS小功能系列2商品计算

 <style>
        li{
            list-style-type:none;
        }
        li span {
             30px;
            text-align: center;
            display: inline-block;
        }
    </style>
</head>

<body>
    <ul class="ul">
        <li>
            <input type="button" value="-">
            <span>4</span>
            <input type="button" value="+"> 单价 :
            <span>15</span> 小计 :
            <span></span>;
        </li>
        <li>
            <input type="button" value="-">
            <span>1</span>
            <input type="button" value="+"> 单价 :
            <span>10</span> 小计 :
            <span></span>;
        </li>
        <li>
            <input type="button" value="-">
            <span>1</span>
            <input type="button" value="+"> 单价 :
            <span>5</span> 小计 :
            <span></span>;
        </li>
    </ul>
    <div class="shop">
          <ul>
              <li>商品数量:<span></span></li>
              <li>一共花费:<span></span>元</li>
              <li>最高的商品单价:<span></span></li>
          </ul>
    </div>


    <script>
        var ali = document.querySelectorAll(".ul li"),
            shopSpan = document.querySelectorAll(".shop span"),
            shop=document.querySelector(".shop");
         
        function smallCount() {
            var totalPrice = 0,
                totalCount = 0,
                maxPrice = 0;
            for (var i = 0, len = ali.length; i < len; i++) {
                var count = parseInt(ali[i].children[1].innerHTML),
                    price = parseInt(ali[i].children[3].innerHTML);
                //小计
                ali[i].children[4].innerHTML = count * price;
                //商品总数量
                totalCount += count;
                //总花费
                totalPrice += parseInt(ali[i].children[4].innerHTML);
                //最高商品单价  15>0  maxPrice=15; 10>15
                if (price > maxPrice) {
                    maxPrice = price;
                }
            }
            shopSpan[0].innerHTML=totalCount;
            shopSpan[1].innerHTML=totalPrice;
            shopSpan[2].innerHTML=maxPrice;
        }
        smallCount();

        for (var i = 0, len = ali.length; i < len; i++) {
            //增加商品数量
            ali[i].children[0].onclick = function () {
                var count = this.parentNode.children[1].innerHTML;
                count--;
                if (count < 0) count = 0;
                this.parentNode.children[1].innerHTML = count;
                smallCount();
            }
            //减少商品数量
            ali[i].children[2].onclick = function () {
                var count = this.parentNode.children[1].innerHTML;
                count++;
                this.parentNode.children[1].innerHTML = count;
                smallCount();
            }
        }

    </script>
</body>

</html>

原文地址:https://www.cnblogs.com/xingkongly/p/7603646.html