你需要给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我刚更新了答案。请检查一次?这是我的一个小错误。 –