JavaScript计算返回NaN [英] JavaScript calculation returns NaN

查看:57
本文介绍了JavaScript计算返回NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到在数组中传递字段值的总和.如果该字段是打折的,则执行减号else加号.出于某种原因,我变得难为情了.

I want to find total sum of passing the field values in array. If the field is for discount then perform minus else plus. For some reason I'm getting nan.

<script>

    var partial_cost = $('#bill_amount:disabled').val();
    var fine = +$('#fine').val();
    var discount = +$('#discount').val();
    var other_cost = +$('#other_cost').val();
    var total_cost = +$('#total').val();

    var chargeAble = [
    partial_cost,
    fine,
    discount,
    other_cost
    ];

    $.each(chargeAble, function (chargeIndex, charge) {
        charge.blur(function () {
            var amount = 0;
            for(charge in chargeAble)
                if(chargeAble[charge].attr('id') == 'discount')
                    amount -= (chargeAble[charge].val());
                else
                    amount += (chargeAble[charge].val());

                total_cost.val(amount);
            });
    });

</script>

推荐答案

代码使用了 .each()和for-in循环的组合...奇怪的是, blur()函数?可以这样简化:

The code is using a combination of .each() AND a for-in loop... and strangely the callback from a blur() function? It can be simplified like this:

var amount = 0;
$('#bill_amount:disabled, #fine, #discount, #other_cost')
  .blur()
  .each(function() {
    var sign = this.id === 'discount' ? -1 : 1;
    amount += parseFloat($(this).val()) * sign;
  });
$('#total').val(amount);


更新:

哦,您希望总数在模糊时更新...尝试以下代码:

Oh, you want the total to update on blur... try this code:

var $values = $('#bill_amount:disabled, #fine, #discount, #other_cost');
$values.on('blur', function() {
  var amount = 0;
  $values.each(function(){
    var sign = this.id === 'discount' ? -1 : 1;
    amount += parseFloat($(this).val()) * sign;
  });
  $('#total').val(amount);
});

这篇关于JavaScript计算返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆