jQuery实现购物车商品数量及总价的计算

记录一下项目中遇到的计算购物车商品数量和总价的jQuery代码,重点在于选择器以及.text()命令的使用。

先上效果图,点击加减,商品数量以及总价会发生相应变化。

html

 1  <div class="details-right fl">
 2             <h2 class="album-name mb20">【独家发售】大张伟2018全新专辑《人间精品》</h2>
 3             <ul class="album-info-li">
 4                 <li><span class="li-name">商城价格</span><strong class="li-price">83.1元</strong>
 5                     <del class="original-price">83.1元</del>
 6                 </li>
 7                 <li><span class="li-name">重量</span><span class="li-info">0.33kg</span></li>
 8                 <!--<li><span class="li-name">数量</span><span class="li-info"><img src="img/num.jpg"/></span></li>-->
 9                 <li class="count">
10                     <span class="li-name">数量</span>
11                     <a href="javascript:void(0);" class="c_sub"> - </a><input id="count-ipt" type="text" value="1"><a href="javascript:void(0);" class="c_add"> + </a>
12                     <span class="inventory">库存<i class="in-count">5</i></span>
13                 </li>
14             </ul>
15             <div class="details-btn-box">
16                 <div class="btns mb20">
17                     <button class="add-cart"></button>
18                     <button class="buy-now"></button>
19                 </div>
20                 <div><img src="img/zpbz.png"/></div>
21 
22             </div>
23         </div>

 

 

css

 1 .count a {
 2     display: inline-block;
 3     width: 24px;
 4     height: 30px;
 5     background: #eaeaea;
 6     color: #fff;
 7     vertical-align: middle;
 8     text-align: center;
 9     font-size: 20px;
10     line-height: 25px;
11     cursor: pointer;
12 }
13 
14 .count input {
15     width: 42px;
16     height: 28px;
17     border: 1px solid #c9c9c9;
18     color: #333739;
19     vertical-align: middle;
20     text-align: center;
21     font-size: 14px;
22 }
23 
24 .count .inventory {
25     margin-left: 15px;
26     color: #999;
27     font-size: 12px;
28 }
29 
30 .count .inventory .in-count {
31     color: #666;
32     font-style: normal
33 }

 

 

js

$(function () {
    $(".c_add").click(function () {
        var val = $("#count-ipt").val();
        var num = parseInt(val) + 1;
        var count = $(".in-count").text();
        if (num <= count)
            $("#count-ipt").val(num)
    })
    $(".c_sub").click(function () {
        var val = $("#count-ipt").val();
        var num = parseInt(val) - 1;
        if (num > 0)
            $("#count-ipt").val(num)
    })


    $(".buy-now").click(function () {
        var val = $("#count-ipt").val();
        var price = parseFloat($(".li-price").text()) * 100;
        alert(val * price / 100);
    })
})

 

posted @ 2021-11-16 19:40  小小不小阿  阅读(556)  评论(0编辑  收藏  举报