【问题标题】:Rewriting JavaScript code with consequent numbers in the names of ids用 id 名称中的后续数字重写 JavaScript 代码
【发布时间】: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


【解决方案1】:

增加 ID 的麻烦多于其价值,尤其是当您开始删除行以及添加行时。

这一切都可以使用通用类并在特定行实例中遍历来完成。

要考虑未来的行,请使用事件委托

简化示例:

// store a row copy on page load
const $storedRow = $('#myTable tr').first().clone()

// delegate event listener to permanent ancestor
$('#myTable').on('input', '.qty, .price', function(){
    const $row = $(this).closest('tr'),
          price = $row.find('.price').val(),
          qty =  $row.find('.qty').val();
    $row.find('.total').val(price*qty)
});

$('button').click(function(){
  // insert a copy of the stored row
  // delegated events will work seamlessly on new rows also
  const $newRow = $storedRow.clone();
  const prodName = 'Product XYZ';// get real value from user input
  $newRow.find('.prod-name').text(prodName)// 
  $('#myTable').append($newRow)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add row</button>

<table id="myTable">
  <tr>
    <td class="prod-name">Product 1</td>
    <td>Qty:<input type="number" class="qty" value="0"></td>
    <td>Price:<input type="number" class="price" value="0"></td>
    <td>Total:<input type="text" class="total" value="0" readonly></td>
  </tr>
  <tr>
     <td class="prod-name">Product 2</td>
    <td>Qty:<input type="number" class="qty" value="0"></td>
    <td>Price:<input type="number" class="price" value="0"></td>
    <td>Total:<input type="text" class="total" value="0" readonly></td>
  </tr>
  
</table>

Understanding Event Delegation

【讨论】:

  • 查理,非常感谢!奇迹般有效! :-)
【解决方案2】:

首先要考虑的是你可以得到一个选择器的length。比如:

var count = $("input").length; 

如果有,这里的值为1。如果有四个,则值为4

您还可以使用.each() 选项来迭代选择器中的每个项目。

$('#add_field').click(function(){
  var allFields = $('[id^="quantity"]'); 
  allFields.each(function(i, el){
    var c = i + 1;
    $(el).keyup(function() {
      var price = parseFloat($("#price" + c).val());
      var quantity = parseInt($(el).val());
      var value = price * quantity;
      value = value.toFixed(2);
      value = value.toString().replace(/\./g, ',');
      $("#value" + c).val(value);
    });
  });
});

您还可以根据 ID 本身创建关系。

$(function() {
  function calcTotal(price, qnty) {
    return (parseFloat(price) * parseInt(qnty)).toFixed(2);
  }

  $('#add_field').click(function() {
    var rowClone = $("#row-1").clone(true);
    var c = $("tbody tr[id^='row']").length + 1;
    rowClone.attr("id", "row-" + c);
    $("input:eq(0)", rowClone).val("").attr("id", "prod_num-" + c);
    $("input:eq(1)", rowClone).val("").attr("id", "price-" + c);
    $("input:eq(2)", rowClone).val("").attr("id", "quantity-" + c);
    $("input:eq(3)", rowClone).val("").attr("id", "value-" + c);
    $("button", rowClone).attr("id", "remove-" + c);
    rowClone.appendTo("table tbody");
  });

  $("table tbody").on("keyup", "[id^='quantity']", function(e) {
    var $self = $(this);
    var id = $self.attr("id").substr(-1);
    if ($("#price-" + id).val() != "" && $self.val() != "") {
      $("#value-" + id).val(calcTotal($("#price-" + id).val(), $self.val()));
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field">Add Field</button>
<br />
<h2>Product</h2>
<table>
  <thead>
    <tr>
      <td>Number</td>
      <td>Name</td>
      <td>Price</td>
      <td>Quantity</td>
      <td>Total</td>
      <td></td>
  </thead>
  <tbody>
    <tr id="row-1">
      <td><input type="text" name="prod_num[]" id="prod_num-1" placeholder="Product number (6 digits)"></td>
      <td><input type="text" name="prod_name[]" disabled></td>
      <td><input type="text" name="cena[]" id="price-1" placeholder="Enter your price"></td>
      <td><input type="text" name="quantity[]" id="quantity-1" placeholder="Enter quantity"></td>
      <td><input type="text" name="value[]" id="value-1" disabled></td>
      <td><button type="button" name="remove_field" id="remove-1" class="button_remove">X</button></td>
    </tr>
  </tbody>
</table>

【讨论】:

  • 感谢您的努力,但这段代码有问题,就最终结果而言,它与我取得的成就相距不远。如果您添加更多行,则计算错误...
猜你喜欢
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多