你需要給click事件裏面的變量聲明:
var qty = parseInt($('.qty').val());
var price = parseFloat($('#price').val());
的原因是,你是靜態在第一負荷的值設置爲0.00
。每次增加或減少時,值都不會改變。它被設置一次,並在更改時不設置。點擊事件發生後,它們不會動態更改。
解決的辦法是把上面兩行寫入.click()
函數中。
jQuery(document).ready(function(){
$("#price").each(function(){
total += parseFloat(this.value);
});
// This button will increment the value
$('.qtyplus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
qty = parseInt($('.qty').val());
price = parseFloat($('#price').val());
$('#total').val((qty * price ? qty * price : 0).toFixed(2));
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
qty = parseInt($('.qty').val());
price = parseFloat($('#price').val());
$('#total').val((qty * price ? qty * price : 0).toFixed(2));
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
qty = parseInt($('.qty').val());
price = parseFloat($('#price').val());
$('#total').val(((qty * price > 0) ? qty * price : 0).toFixed(2));
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
qty = parseInt($('.qty').val());
price = parseFloat($('#price').val());
$('#total').val(((qty * price > 0) ? qty * price : 0).toFixed(2));
}
});
});
工作小提琴:http://jsfiddle.net/txk2d85y/
它仍然似乎並沒有正常工作......當我是遞減不會減少總數,也不會添加兩個文本框來創建總數...在0它只顯示21 .. – iyuyguyg
@iyuyguyg我剛更新了答案。請檢查一次?這是我的一個小錯誤。 –