我收到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>
Run Code Online (Sandbox Code Playgroud)
这是jquery
$(function() {
$('.box').change(function(){
var total = 0;
$('.box:checked').each(function(){
total+=parseFloat($(this).parent().next('td').find('.amount').text());
});
$('#total').text(total);
});
});
Run Code Online (Sandbox Code Playgroud)
我在总元素中得到NaN.
让我们分解你的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
Run Code Online (Sandbox Code Playgroud)
您需要做的是将其附加.amount到您的选择器上,然后使用nextAll,如下所示:
$(this).parent().nextAll("td.amount").text()
Run Code Online (Sandbox Code Playgroud)
如果你有多个amount课程,你需要确保你只选择了第一个课程:
$(this).parent().nextAll("td.amount:first").text()
Run Code Online (Sandbox Code Playgroud)
例:
$('.box').change(function(){
var total = 0;
$('.box:checked').each(function(){
total+=parseFloat($(this).parent().nextAll('td.amount').text());
});
$('#total').text(total);
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |