【问题标题】:jQuery selector with sum带有总和的 jQuery 选择器
【发布时间】:2012-07-24 10:04:33
【问题描述】:

我不知道我的问题的好标题,这就是我没有搜索的原因。

我的问题如下:

我有一个 HTML 代码,例如:

<input type="text" id="product_qty_1" value="12" />
<input type="text" id="product_qty_2" value="21" />
<input type="text" id="product_qty_3" value="45" />

我想通过 jQuery 对值求和,但这需要自动进行,因为我们不知道有多少 inputs

我不知道,如何处理选择器 input[id*="product_qty_"] 以使其正常工作,并对值求和!

提前致谢!

【问题讨论】:

    标签: javascript jquery html sum


    【解决方案1】:

    你可以使用 jQuery 的 each 循环:

    var sum = 0;
    $('input[id*="package_qty_"]').each(function() {
        sum += parseInt(this.value, 10);
    });
    alert(sum);
    

    【讨论】:

      【解决方案2】:
      var total=0;
      
      $("input[type='text']").each(function() {
          total += parseInt(this.value, 10);
      });
      

      【讨论】:

      • +1 用于使用this.value 而不是$(this).valueparseInt(.., 10)
      • 可选的错误保护:当值不是数字时,使用total += parseInt(this.value, 10) || 0; 来避免尴尬的“NaN”结果。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2014-07-19
      • 1970-01-01
      • 2019-12-16
      • 2011-09-29
      • 1970-01-01
      相关资源
      最近更新 更多