2015-08-28 37 views
0

我得到一個NaN錯誤。該代碼是從一個完美的小提琴複製。這是代碼。javascript得到一個表列總NaN錯誤

<tbody> 
      <tr> 
      <td><input type="checkbox" name="payment_id[]" id="payment_id_" value="6" class="box" checked="checked" /></td>     
      <td>2015-08-26 20:43:50 UTC</td> 
      <td>1000002043</td> 
      <td class = "amount">25.0</td> 
      <td>CHK</td> 
      <td></td> 
      <td></td> 
      <td>5</td> 
      <td><a href="/payments/6">Show</a></td> 
      <td><a href="/payments/6/edit">Edit</a></td> 
      <td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/payments/6">Destroy</a></td> 
      </tr> 
     <% end %> 
     </tbody> 
     <td>Total</td><td><div id="total"></div></td> 

這裏是jQuery的

$(function() { 
$('.box').change(function(){ 

    var total = 0; 
    $('.box:checked').each(function(){ 
     total+=parseFloat($(this).parent().next('td').find('.amount').text()); 
    });  
    $('#total').text(total); 
}); 
}); 

我得到一個楠元件的整體。

回答

6

讓我們打破你的jQuery鏈:

$(this) // ,box 
    .parent() // The <td> 
    .next('td') // The next <td> in the sequence 
    .find('.amount') // Tries to find an element with class `amount` inside the <td> 
    .text() // Empty, because the previous element doesn't exist 

什麼你需要做的是.amount添加到您的選擇和使用nextAll代替,就像這樣:

$(this).parent().nextAll("td.amount").text() 

如果你有多個amount類,你需要確保你只挑這樣的第一個:

$(this).parent().nextAll("td.amount:first").text() 

例子:

$('.box').change(function(){ 
 

 
    var total = 0; 
 
    $('.box:checked').each(function(){ 
 
     total+=parseFloat($(this).parent().nextAll('td.amount').text()); 
 
    });  
 
    $('#total').text(total); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
<tbody> 
 
      <tr> 
 
      <td><input type="checkbox" name="payment_id[]" id="payment_id_" value="6" class="box" checked="checked" /></td>     
 
      <td>2015-08-26 20:43:50 UTC</td> 
 
      <td>1000002043</td> 
 
      <td class = "amount">25.0</td> 
 
      <td>CHK</td> 
 
      <td></td> 
 
      <td></td> 
 
      <td>5</td> 
 
      <td><a href="/payments/6">Show</a></td> 
 
      <td><a href="/payments/6/edit">Edit</a></td> 
 
      <td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/payments/6">Destroy</a></td> 
 
      </tr> 
 
     </tbody> 
 
</table> 
 
<div id="total"></div>

0

考慮到金額輸入每行一次我跳回到行,發現該行的td.amount。

(function($) { 
    $('.box').change(function(){ 
     var total = 0; 
     $('.box:checked').each(function(){ 
      total += parseFloat($('td.amount', $(this).closest('tr')).text()); 
     });  
     $('#total').text(total); 
    }); 
})(jQuery); 
0

存在引用錯誤。使用方法:

$(function() { 
$('.box').change(function(){ 

    var total = 0; 
    $('.box:checked').each(function(){ 
     total+=parseFloat($(this).closest('tr').find('td.amount').text()); 
    });  
    $('#total').text(total); 
}); 
});