如何调用每个字段集的汇总值

时间:2016-07-04 04:50:24

标签: javascript jquery

我有一个示例代码:

<fieldset class="accessory">
   <legend>Premium</legend>
   Premium Soup 1 <input type="text" name="quantity[]" value="1" class="value_quantity">
   Premium Soup 2 <input type="text" name="quantity[]" value="1" class="value_quantity">  
</fieldset>
<fieldset class="accessory">
   <legend>Premium</legend>
   Chicken Rice 1 <input type="text" name="quantity[]" value="2" class="value_quantity">
   Chicken Rice 2 <input type="text" name="quantity[]" value="2" class="value_quantity"> 
   Chicken Rice 3 <input type="text" name="quantity[]" value="1" class="value_quantity"> 
</fieldset>

这是我的jquery:

$('.accessory').each(function (index, element) {
   var group_quantity = 0;
   $('.value_quantity').each(function (key, val){
      group_quantity = group_quantity + parseInt($(val).val());        
   });
   console.log("Group" + index + ':' + group_quantity);
});

我希望结果如下:

Group 1 : 2
Group 2 : 5

但我的剧本不正确。如何解决?

1 个答案:

答案 0 :(得分:1)

在迭代this时考虑.value_quantity上下文,这将仅选择父children .accessory的那些元素,否则将选中所有.value_quantity在操纵时。

  

jQuery( selector [, context ] ) 接受包含CSS selector的字符串,然后将其用于匹配一组elementscontextDOM ElementDocumentjQuery,可用作上下文。

  

.each()方法旨在使DOM looping构造简洁且不易出错。调用时,它会遍历属于jQuery对象的DOM elements。每次回调运行时,都会从0开始传递当前循环迭代。更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字 {{1 是指元素

this
$('.accessory').each(function(index, element) {
  var group_quantity = 0;
  $('.value_quantity', this).each(function(key, val) {
    //_______________^^^^^^
    //OR $(this).find('.value_quantity').each(function...
    group_quantity = group_quantity + parseInt($(val).val());
  });
  console.log("Group" + index + ':' + group_quantity);
});

简化版:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<fieldset class="accessory">
  <legend>Premium</legend>
  Premium Soup 1
  <input type="text" name="quantity[]" value="1" class="value_quantity">Premium Soup 2
  <input type="text" name="quantity[]" value="1" class="value_quantity">
</fieldset>
<fieldset class="accessory">
  <legend>Premium</legend>
  Chicken Rice 1
  <input type="text" name="quantity[]" value="2" class="value_quantity">Chicken Rice 2
  <input type="text" name="quantity[]" value="2" class="value_quantity">Chicken Rice 3
  <input type="text" name="quantity[]" value="1" class="value_quantity">
</fieldset>
$('.accessory').each(function(index, element) {
  var group_quantity = 0;
  $('.value_quantity', this).each(function() {
    group_quantity += +this.value;
  });
  console.log("Group" + index + ':' + group_quantity);
});