[英]JavaScript Calculate total price of items
請幫我輸入所選商品的總價。 這是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);
});
此代碼將動態工作。 即使你添加或刪除項目,它應該工作。
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>
檢查演示
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+'$');
}
});
}
我已經在.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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.