在以下代码中,运行时,totalQuantity、totalCost这两个变量总是在网页上显示NaN这个值,而不是我设想的让它计算出各行的总和。但是如果我把这两个语句“ totalQuantity+=quantity; totalCost+=cost;”改成“ totalQuantity=quantity; totalCost=cost;”时,它是会显示出循环的最后一行的值。所以是不是这两个语句“ totalQuantity+=quantity; totalCost+=cost;”有什么问题还是其它的原因呢
$('.Gquantity input').keypress(function(event){
if(event.which&&(event.which<48||event.which>57)){
event.preventDefault();
}
}).change(function(){
var totalQuantity = 0;<!--所有商品的数量-->
var totalCost = 0;<!--所有商品的金额-->
<!---通过用户对商品数量选择的变换来计算对应的金额->
$('#cart tbody tr').each(function() {
var price = parseFloat($('.Gprice',this).text().replace(/^[^\d.]*/,''));
price = isNaN(price)? 0:price;
var quantity = parseInt($('.Gquantity input',this).val(),10);
var cost = quantity * price;
$('.Gcost',this).text('¥'+cost.toFixed(2));
totalQuantity+=quantity;
totalCost+=cost;
//<!--对应商品总额的计算-->
});
alert(totalCost);
$('#subtotalcost').text('¥'+totalCost.toFixed(2));<!--原价总额-->
$('#totalquantity').text(totalQuantity);<!--总数量-->
<!--优惠金额的计算-->
// var count = parseFloat($('.count.Gcost').text().replace(/^[^\d.]*/,''));
// totalCost += count;
<!--运费的计算-->
$('#shippingquantity').text(String(totalQuantity));
var shippingRate = parseFloat($('#shippingprice').text().replace(/^[^\d.]*/,''));
var shipping = totalQuantity * shippingRate;
$('#shippingcost').text('¥'+shipping.toFixed(2));
totalCost += shipping;
<!--实际所需付款金额-->
$('#tatal').text('¥'+totalCost.toFixed(2));
});
JavaScript函数
$('.Gquantity input').keypress(function(event){
if(event.which&&(event.which<48||event.which>57)){
event.preventDefault();
}
}).change(function(){
var totalQuantity = 0;<!--所有商品的数量-->
var totalCost = 0;<!--所有商品的金额-->
<!---通过用户对商品数量选择的变换来计算对应的金额->
$('#cart tbody tr').each(function() {
var price = parseFloat($('.Gprice',this).text().replace(/^[^\d.]*/,''));
price = isNaN(price)? 0:price;
var quantity = parseInt($('.Gquantity input',this).val(),10);
var cost = quantity * price;
$('.Gcost',this).text('¥'+cost.toFixed(2));
totalQuantity+=quantity;
totalCost+=cost;
//<!--对应商品总额的计算-->
});
alert(totalCost);
$('#subtotalcost').text('¥'+totalCost.toFixed(2));<!--原价总额-->
$('#totalquantity').text(totalQuantity);<!--总数量-->
<!--优惠金额的计算-->
// var count = parseFloat($('.count.Gcost').text().replace(/^[^\d.]*/,''));
// totalCost += count;
<!--运费的计算-->
$('#shippingquantity').text(String(totalQuantity));
var shippingRate = parseFloat($('#shippingprice').text().replace(/^[^\d.]*/,''));
var shipping = totalQuantity * shippingRate;
$('#shippingcost').text('¥'+shipping.toFixed(2));
totalCost += shipping;
<!--实际所需付款金额-->
$('#tatal').text('¥'+totalCost.toFixed(2));
});
JavaScript函数
$('.Gprice',this).text()
$('.Gquantity input',this).val()可能是取不到值或者.Gprice,.Gquantity元素不存在
最好是先用正则验证输入的内容,然后 计算的时候用 parseInt("123") 或者parseFlost("123") 根据你实际的类型来进行转换。