Javascript jQuery价格计算器
我正在尝试创建一个简单的jQuery计算器,但它似乎没有像我希望的那样工作。基本上,它应该自动计算输入框中的0价格,然后在单击+/-时相乘 它似乎没有做任何事情或显示任何错误Javascript jQuery价格计算器,javascript,jquery,html,calculator,Javascript,Jquery,Html,Calculator,我正在尝试创建一个简单的jQuery计算器,但它似乎没有像我希望的那样工作。基本上,它应该自动计算输入框中的0价格,然后在单击+/-时相乘 它似乎没有做任何事情或显示任何错误 jQuery(document).ready(function(){ var qty = parseInt($('.qty').val()); var price = parseFloat($('#price').val()); $("#price").each(function(
jQuery(document).ready(function(){
var qty = parseInt($('.qty').val());
var price = parseFloat($('#price').val());
$("#price").each(function(){
total += parseFloat(this.value);
});
我不确定我是否考虑过度了,有人有什么想法吗?您需要在单击事件中给出变量声明:
var qty = parseInt($('.qty').val());
var price = parseFloat($('#price').val());
原因是,您在第一次加载时静态地将值设置为0.00
。每次递增或递减时,值都不会更改。设置一次,更改时不设置。在触发单击事件后,它们不会动态更改
解决方案是将上述两行放在函数中。单击()
函数
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));
}
});
});
工作提琴:我不确定为什么您有两个价格框,但我已将提琴更新为1,因为这会导致一些异常行为 但是,问题的根源在于,您已在document.ready上声明了
quaty
和price
,但每次单击按钮时都不会更新它们。下面是一个小提琴演示了一种解决方案:
然而,我觉得你可以把整个过程缩短得更简洁,减少加号和减号按钮之间代码的重复。请继续关注带有推荐的更新
更新
以下是重构版本:
我所做的更改是:
,我已经这样做了adjustQty
函数adjustQty
功能计算新的总数,并更新文本框唯一真正的区别是,它在乘以数量之前计算两个价格框的总数。jQuery提供了一个插件,可以帮助您:“jQuery Calx” 请看这里的演示:
http://prototype.xsanisty.com/calx2/
它似乎仍然不能正常工作。。。当我减少时,它不会减少总数,也不会添加两个文本框来创建总数。。。在0时,它只显示21..@iy维吾尔我刚刚更新了答案。请检查一下好吗?这是我的一个小错误。