使用 jQuery 添加新输入字段时如何计算总数

0 html javascript jquery

$(document).ready(function(){

   $(".price2").keyup(function(){
       total = parseInt($(".price1").val()) + parseInt($(".price2").val());
       $(".total").val(total);
   });
    
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="price1" >
<input type="text" class="price2" >
<input type="text" class="total" >
Run Code Online (Sandbox Code Playgroud)

此代码片段执行两个字段的添加并将总数添加到第三个。好的,这看起来不错,但问题是当我使用 jQuery 添加新字段时,总不能工作。即使我使用 jQuery 添加新的输入字段,我应该怎么做才能添加总数

你可以通过下图更好地理解 在此处输入图片说明

我通过以下代码添加新字段

var i = 0;
   $("#addmore").click(function() {
     $("#inputtabletable tr:first").clone().find(".webfield").each(function() {
       $(this).val('').attr({
         'id': function(_, id) {
           return id + i
         },
         'name': function(_, name) {
           return name + i
         },
         'value': ''
       });
     }).end().appendTo("#inputtabletable");
     i++;
   });
Run Code Online (Sandbox Code Playgroud)

使用 jQuery 添加新字段时如何添加总计

Sre*_*nth 5

您的用例需要对您的 html 和 javascript 进行一些更改,它无法开箱即用。您需要利用事件委托并从将来创建的元素中捕获事件。

更多关于委托的信息可以在这里找到jQuery .on

$(document).ready(function() {

  $('.addition').on('keyup', '.price', function() {
    var total = 0
    $('.addition > .price').each(function() {
      var currentValue = parseInt($(this).val(), 10);
      if (!isNaN(currentValue)) {
        total += currentValue;
      }
    });
    $(".total").val(total);
  });
  $('.add').click(function() {
    $("<input type='text' class='price'>").appendTo($('.addition'));
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='addition'>
  <input type="text" class="price">
  <input type="text" class="price">
</div>
Total: <input type="text" class="total">
<button class='add'>Add</button>
Run Code Online (Sandbox Code Playgroud)