我在 jQuery 方面没有太多经验,我面临以下挑战
我有下表
<table>
<thead>
<tr>
<td>Qty</td>
<td>Description</td>
<td>Unit Price</td>
<td>Total Price</td>
<tr>
</thead>
<tbody>
<tr id="itemRow">
<td><input type="text" name="quantity"/></td>
<td><input type="text" name="description"/></td>
<td><input type="text" name="unitPrice"/>/td>
<td><input type="text" name="totalPrice"/></td>
<tr>
</tbody>
</table>
<input type="text" name="total"/>
此外,我可以根据需要多次克隆#itemRow,从而增加项目的数量。
想法是计算每一行的总价(按数量
* unitPrice
)并将其分配给totalPrice
。并将 totalPrice
的总和分配给 total
。
这是我正在使用的 javascript,但我收到一条错误消息“cantidades[i].val() is not a function”
function calculate(){
var $total = $('#total');
var $cantidades = $('input[name=quantity]')
var $unitarios = $('input[name=unitPrice]')
var $totales = $('input[name=totalPrice]')
var len = $cantidades.length;
$total.val(0);
for (var i = 0; i < len; i++){
// calculate total for the row. ERROR HERE!
$totales[i].val($cantidades[i].val() * $unitarios[i].val());
// Accumulate total
$total.val($totalExento.val() + $totales[i].val());
}
}
我错过了什么?我认为我没有从选择器中获取“jQuery 对象”,但我不确定是否热衷于这样做。
提前致谢!
最佳答案
这一行:var $cantidades = $('input[name=quantity]')
检索一个无法像使用 $cantidades[i]
那样访问的 jQuery 实例.
像这样修复它:
var singleElementCantidades = $($cantidades[i]);
singleElementCantidades.val();
发生的事情是$('input[name=quantity]')
检索作为 jQuery 实例的数组。当您使用 cantidades[i] 访问它的内容时,您不再管理 jQuery 实例,您正在访问其他没有 val 定义的东西。
关于javascript - 查询 : Product between 2 lists of inputs into a 3rd list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37580293/