【问题标题】:jquery: Summing values after dynamic delete of content gets NaNjquery:动态删除内容后求和值得到NaN
【发布时间】:2015-04-14 12:24:00
【问题描述】:

这是我的 js:

function sumAllFields() {
    var priceSum = 0;
    $(".price").each(function () {
        var o = $(this).parent().parent().index();
        priceSum += Number($("#area" + o).text()) * $("#price" + o).val();
    })
    $("#sumPrice, #printSumPrice").html(priceSum.toFixed(2));
}    

这里是相关的html:

<tbody id="tableBody">
<tr class="tableRow" id="tableRow0"> 
    <td><input class="idNumber" id="idNumber0" type="number"></td>
    <td><input class="description" id="description0" type="text"></td>
    <td class="dimA" id="dimA0">520</td>
    <td class="dimB" id="dimB0">785</td>
    <td><input class="pcs" id="pcs0" type="number"></td>
    <td class="area" id="area0">2.46</td>
    <td><input class="price" id="price0" type="number"></td>
    <td class="noprint"><span class="closed">×</span></td>                         
</tr>

<!-- and a few more in between... -->

<tr class="tableRow" id="tableRow8">
    <td><input class="idNumber" id="idNumber8" type="number"></td>
    <td><input class="description" id="description8" type="text"></td>
    <td class="dimA" id="dimA8">510</td>
    <td class="dimB" id="dimB8">785</td>
    <td><input class="pcs" id="pcs8" type="number"></td>
    <td class="area" id="area8">0.80</td>
    <td><input class="price" id="price8" type="number"></td>
    <td class="noprint"><span class="closed">×</span></td>                         
</tr>
</tbody>

我要做的是在动态删除一个&lt;tr&gt; 后自动对所有.price 字段求和,而我得到的只是NaN。在我删除任何行之前,我得到了一个不错的数字,但在我删除任何行之后,我得到了 NaN。

【问题讨论】:

  • 它是否解决了您的问题:priceSum += Number($("#area" + o).text()) * $("#price" + o).val() || 0;?!
  • 部分地,我不再得到 NaN,但我也没有得到正确的总和。

标签: javascript jquery nan


【解决方案1】:

这是因为您用于查找兄弟price/area 元素的逻辑。假设您添加了 4 个项目,因此您有像 area0/area1/area2/area3 这样的元素。现在您正在删除第 2 行,因此元素 area1 不再存在,然后在第二次迭代中的每个循环中 o 变为 1 然后它尝试查找元素 #area1 但没有这样的元素导致 @987654327 @返回NaN.

试试

function sumAllFields() {
    var priceSum = 0;
    $(".price").each(function () {
        var $tr = $(this).closest('tr');
        priceSum += (+$tr.find(".area").text() * +this.value) || 0;
    })
    $("#sumPrice, #printSumPrice").html(priceSum.toFixed(2));
}

演示:Fiddle

【讨论】:

    【解决方案2】:

    让我们直接迭代表行:

    function sumAllFields() {
      var priceSum = 0;
      $('.tableRow').each(function () {
        var row = $(this);
        priceSum += (parseFloat(row.find('.area').text())
          * parseFloat(row.find('.price').val())) || 0;
      })
      $('#sumPrice, #printSumPrice').html(priceSum.toFixed(2));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多