簡體   English   中英

JavaScript計算返回NaN

[英]JavaScript calculation returns NaN

我想找到在數組中傳遞字段值的總和。 如果該字段是打折的,則執行減號else加號。 由於某種原因,我變得難為情。

這是我的腳本代碼

<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>

我到處都能看到這樣的東西:

var fine = +$('#fine');

jQuery()方法返回jQuery對象,而不是數字甚至字符串。 因此,強制數字轉換將返回NaN

您需要先抓取其中的文本,然后解析出其中的數字。 如何執行取決於您HTML的結構,但一般來說:

  • 在表單字段中,您通常可以使用.val()
  • 在大多數其他標簽中,您可以使用.text()

代碼使用.each()和for-in循環的組合...奇怪的是來自blur()函數的回調? 可以這樣簡化:

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);

更新:

哦,您希望總數在模糊時更新...嘗試以下代碼:

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將所有值都解釋為數字。 否則,它將嘗試從字符串中計算出一些奇怪的結果,該結果可能會被解釋為十進制數(十六進制,八進制等)之外的其他值。

您的數組包含數字,並且您的行為就像字符串一樣

var chargeAble = [  //this holds values
    partial_cost,
    fine,
    discount,
    other_cost
];

並在循環中,您將其用作ID ???

chargeAble[charge].attr('id') 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM