给出这个HTML:
<table class="hours-table">
<tr>
<th>Hours</th>
<th>Hourly Rate</th>
<th>Date Total</th>
</tr>
<tr>
<td class="hours"><input type="text" class="hours" name="hours-01" value="" /></td>
<td class="rate"><input type="text" class="rate" name="rate-01" value="" /></td>
<td class="date-total"><input type="text" class="date-total" name="date-total-01" value="" /></td>
</tr>
</table>
<p><a class="calculate" href="#" title="calculate row">Calculate</a></p>
Run Code Online (Sandbox Code Playgroud)
我正在尝试循环遍历行,获取每行中的小时和费率值,将它们相乘并在'date-total'输入中设置该值(不一定必须是总数的输入,但我会在多列上进行另一次计算)
几个小时我的头颅为什么一千次尝试获取这些值都没有用,例如:
$('.calculate').on('click', function() {
$('.hours-table tr').each(function() {
var hours = $(this).find('input.hours').val(); // nope
var hours = $('input.hours', this).val(); // nope
var hours = $('input.hours', $this).val(); // nope
//var dateTotal = (hours * rate);
//$(this).find('input.date-total').val(dateTotal);
return false;
}) //END .each
}) // END click
Run Code Online (Sandbox Code Playgroud)
拜托,我对这个循环做错了什么?
return false;
在$.each
循环中使用将退出它.我认为你的意思return false;
是为了click
处理程序 - 防止默认行为<a>
并停止事件传播.因此,如果你return false;
移出一个级别,它似乎工作:
$(document).ready(function () {
$('.calculate').on('click', function() {
$('.hours-table tr').each(function() {
var hours = $(this).find('input.hours').val();
var rate = $(this).find('input.rate').val();
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
}); //END .each
return false;
}); // END click
});
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/Lr5pq/1/
更新:
与得到的问题undefined
和NaN
是因为这是选择所有<tr>
元素-包括你的标题行:
<tr>
<th>Hours</th>
<th>Hourly Rate</th>
<th>Date Total</th>
</tr>
Run Code Online (Sandbox Code Playgroud)
由于您的循环在第一行(第一行是标题行)之后立即退出,因此任何console.log
/调试都是针对标题行.当然,没有找到任何元素.要解决这个问题,你应该使用<thead>
并<tbody>
分开目的.所以你的表应该是这样的:
<table class="hours-table">
<thead>
<tr>
<th>Hours</th>
<th>Hourly Rate</th>
<th>Date Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="hours"><input type="text" class="hours" name="hours-01" value="" /></td>
<td class="rate"><input type="text" class="rate" name="rate-01" value="" /></td>
<td class="date-total"><input type="text" class="date-total" name="date-total-01" value="" /></td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
你的tr
选择器应该是:
$('.hours-table').find('tbody').find('tr').each(function() {
Run Code Online (Sandbox Code Playgroud)
(我喜欢使用.find()
而不是长选择器,但关键是你tbody
要将部件添加到目标<tbody>
行中)
演示: http ://jsfiddle.net/Lr5pq/4/