计算总计时获取NaN

问题描述 投票:0回答:2

我试图用数量计算产品价格然后显示总数但是当我计算时我得到结果为NaN

这是代码

$('button').click(function() {
   var total = 0;

   $('#mineraltable tbody tr').each(function(index) {

      var price = parseInt($(this).find('.price').text());
      var quantity = parseInt($(this).find('.quantity input').val());
      var value = $(this).find('.value');
      var subTotal = price * quantity;

      value.text(subTotal);
      total = total + subTotal;
   });

   $('#result').text('Your value is: '+ total);
      console.log(total);
   });

你的价值是:NaN

jquery product invoice calculated-field
2个回答
0
投票

如果您不确定这些字段中可能存在的数据,可以使用IsNaN()并检查文本是否为数字。

$('button').click(function() {
                  var total = 0;

                  $('#mineraltable tbody tr').each(function(index) {
                  var price = 0 , quantity = 0;

                  price = parseInt($(this).find('.price').text());
                  quantity = parseInt($(this).find('.quantity input').val());

                 //check for NaN
                  price = isNaN(price) ? 0 : price;
                  quantity = isNaN(quantity) ? 0 : quantity;

                  var value = $(this).find('.value');
                  var subTotal = price * quantity;

                  value.text(subTotal);
                  total = total + subTotal;
                });

                $('#result').text('Your value is: '+ total);
                console.log(total);

                });

0
投票

请检查您在parseInt函数中传递任何非数值的值。

© www.soinside.com 2019 - 2024. All rights reserved.