我有下表
<table class="authors-list" border=0 id="ordertable">
<tr>
<td>Cubic Meters</td><td>Cubes per Bundle</td><td>Total Bundles</td>
<tr>
<td><input type="text" name="cubicmeters1" id="cubicmeters1" value="1.38"></td>
<td><input type="text" name="cubesperbundle1" id="cubesperbundle1" value="1.485"></td>
<td><input type="text" name="bundles1" id="bundles1"></td>
</tr>
<tr>
<td><input type="text" name="cubicmeters2" id="cubicmeters2" value="1.38"></td>
<td><input type="text" name="cubesperbundle2" id="cubesperbundle2" value="1.485"></td>
<td><input type="text" name="bundles2" id="bundles2"></td>
</tr>
<tr>
<td><input type="text" name="cubicmeters3" id="cubicmeters3" value="1.38"></td>
<td><input type="text" name="cubesperbundle3" id="cubesperbundle3" value="1.485"></td>
<td><input type="text" name="bundles3" id="bundles3"></td>
</tr>
</table>
我想要做的是循环遍历每个表行并对两个输入执行数学函数,并将结果填充到第三个输入中。
fiddle 在这里:http://jsfiddle.net/ttZtX/1/
这是我对 jquery 的尝试:
$("table.authors-list").find('input[name^="cubicmeters1"]').each(function () {
cubes += +$(this).closest('tr').find('input[name^="cubicmeters"]').val();
cubesperbundle += +$(this).closest('tr').find('input[name^="cubesperbundle"]').val();
+$(this).closest('tr').find('input[name^="bundles"]').val((cubes*cubesperbundle).toFixed(2));
});
这不会产生任何结果或错误,并且不会填充输入。
总而言之,我的要求是 jquery 循环遍历每一行,将 cubicmeters 乘以 cubesperbundle 并用结果填充 bundles
。
很简单,但我就是无法正确理解。
如有任何帮助,我们将不胜感激。
提前致谢...
最佳答案
您选择了No wrap - in <head>
在您的 fiddle 中,因此您尝试选择的元素尚未创建,请尝试将其更改为 onDomready
同时删除 1
在$("table.authors-list").find('input[name^="cubicmeters1"]')
选择所有输入而不是仅选择一个并添加 var
在变量之前,这样它们就不会泄漏到全局范围
$("table.authors-list").find('input[name^="cubicmeters"]').each(function () {
var cubes = +$(this).closest('tr').find('input[name^="cubicmeters"]').val();
var cubesperbundle = +$(this).closest('tr').find('input[name^="cubesperbundle"]').val();
$(this).closest('tr').find('input[name^="bundles"]').val((cubes*cubesperbundle).toFixed(2));
});
关于jquery 循环遍历每个表行并对每个行输入字段执行数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203166/