jquery:动态删除内容后的求和值得到NaN

时间:2015-02-13 12:47:15

标签: javascript jquery nan

这是我的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>

我要做的是在动态删除一个.price之后自动对所有<tr>字段求和,而我得到的只是NaN。在我删除任何行之前,我得到一个很好的数字,但在删除任何行后,我得到NaN。

2 个答案:

答案 0 :(得分:0)

这是因为您已经使用逻辑来查找兄弟price/area元素。假设您添加了4个项目,因此您拥有area0/area1/area2/area3等元素。现在您要删除第2行,因此元素area1不再存在,然后在第二次迭代o中的每个循环中变为1然后它会尝试查找元素#area1但是没有这样的导致Number($("#area" + o).text())返回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

答案 1 :(得分:0)

让我们直接迭代表格行:

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