【发布时间】:2021-07-19 07:05:00
【问题描述】:
我正在尝试将函数应用于具有包含后续数字(即 price1、price2、price3)等 id 的输入字段。
为开始定义的第一行字段没有问题。但是更多的输入字段是由 jQuery 函数动态添加的,并且它们的数量是预先不知道的。
我希望这将是一个简单的循环应用:
var i=1;
$("#quantity"+i).keyup(function() {
var price= $("#price"+i).val();
var quantity= $(this).val();
var value= price*quantity;
var value=value.toFixed(2); /* rounding the value to two digits after period */
value=value.toString().replace(/\./g, ',') /* converting periods to commas */
$("#value"+i).val(value);
});
到目前为止一切顺利 - 在“数量”字段被填满后,乘法的结果正确显示在 id="value1" 字段中。
现在其他字段应遵循模式并在输入数量时计算值 - 如下所示:
[price2] * [quantity2] = [value2]
[price3] * [quantity3] = [value3]
等等
所以代码如下:
$('#add_field').click(function(){ /* do the math after another row of fields is added */
var allfields=$('[id^="quantity"]');
var limit=(allfields.length); /* count all fields where id starts with "quantity" - for the loop */
for (var count = 2; count < limit; count++) { /* starting value is now 2 */
$("#quantity"+count).keyup(function() {
var cena = $("#price"+count).val();
var quantity= $("#quantity"+count).val();
var value= price*quantity;
var value=value.toFixed(2);
value=value.toString().replace(/\./g, ',')
$("#value"+count).val(value);
});
}
});
问题在于,只有在(重新)输入“quantity2”并且根本不计算“value2”时,才会计算所有进一步的“value”字段。
我猜在寻址字段和/或触发计算时出现错误。
我应该如何更正代码?
以防万一需要“add_field”函数来解决问题:
$(document).ready(function(){
var i=1;
$('#add_field').click(function(){
i++;
$('#offer').append('<tr id="row'+i+'">
<td><input type="text" name="prod_num[]" id="prod_num'+i+'" placeholder="Product number (6 digits)"></td><td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price'+i+'" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity'+i+'" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value'+i+'" disabled></td>
<td><button type="button" name="remove_field" id="'+i+'" class="button_remove">X</button></td></tr>');
});
【问题讨论】:
-
欢迎来到 Stack Overflow。请提供一个最小的、可重复的示例:stackoverflow.com/help/minimal-reproducible-example您可能还想参加游览:stackoverflow.com/tour
-
ids 与动态创建的元素一起使用很难使用,而且容易出错。您可以利用event delegation 和表格的结构来代替。 -
...你甚至可以使用类来代替:为你想给出编号 ID 的元素应用相同的类,你可以使用类循环遍历元素或访问 nth 具有该类的元素。
标签: javascript jquery loops jquery-selectors