简体   繁体   English

JavaScript计算商品的总价

[英]JavaScript Calculate total price of items

Please help me to type the total price of selected items. 请帮我输入所选商品的总价。 Here is JSFiddle 这是JSFiddle

 <section id="items">
   <div class="item">Monitor <span class="price">100$</span></div>
   <div class="item">Mouse <span class="price">20$</span></div>
   <div class="item">Keyboard <span class="price">60$</span></div>
 </section>
 <section id="basket">
   <p>Total price:<span class="total_price"></span></p>
 </section>`
var total = 0;

$("#items").on('click', ".item", function() {       
    $(this).appendTo("#basket");
    total += parseInt($(this).children().text(), 10);
    $('.total_price').text(total);
});

$("#basket").on('click', ".item", function() {      
    $(this).appendTo("#items");
    total -= parseInt($(this).children().text(), 10);
    $('.total_price').text(total);
});

JSFiddle 的jsfiddle

This code will work dynamically. 此代码将动态工作。 Even if you add or remove items, it should work. 即使你添加或删除项目,它应该工作。

 var priceList = $('#items').find('.price'); var totalPrice = 0; $.each(priceList, function(i, price){ totalPrice += parseInt($(price).text()) }); $('.total_price').text(totalPrice); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <section id="items"> <div class="item">Monitor <span class="price">100$</span></div> <div class="item">Mouse <span class="price">20$</span></div> <div class="item">Keyboard <span class="price">60$</span></div> </section> <section id="basket"> <p>Total price:<span class="total_price"></span></p> </section> 

check demo 检查演示

   var total = 0;
   $("#items").on('click', ".item", function() {        
        $(this).appendTo("#basket");
        getTotal()
   });
    $("#basket").on('click', ".item", function() {      
      $(this).appendTo("#items");   
      getTotal()
   });


  function getTotal(){
     total = 0;
     $("#basket").find('.price').each(function(i){
        total += parseInt($(this).text().slice(0,-1));
        if(i + 1 === $("#basket").find('.item').length){
         $('.total_price').text(total+'$');
       } 
     });
   } 

I have moved '$' outside of the .total_price span 我已经在.total_price范围之外移动了'$'

$("#items, #basket").on('click', ".item", function(){
    $($(this).parent().is('#items')?'#basket':'#items').append(this);   
    $(".total_price").text(getTotal());
});

function getTotal(){
    var t = 0;
    $('.price', "#basket").each(function(){
       t+=parseInt($(this).text());
    });
    return t;
}

JSFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM