如何将jQuery each()隔离到起始元素的父容器的子容器中

时间:2013-04-03 15:36:33

标签: jquery each

在下面的脚本中,我需要更改jQuery each(),以便它不是使用泛型类,而是从目标元素#customfield_11071开始,然后爬到最近的“活动窗格”父元素( .active-pane#tab-5)并且只将带有class =“text.long-field”的子元素输入传递给每个?

我认为通过将#tab-5直接传递到每个它会执行它,但是它拾取与tab-5父容器之外的类匹配的文本输入字段并将它们添加到总容器中,从而产生一个糟糕的计算。

jQuery(document).ready(function(){

        //iterate through each textboxes and add keyup
        //handler to trigger sum event
        jQuery("#tab-5 input.text.long-field").each(function() {

            jQuery(this).keyup(function(){
                calculateSum();
            });
        });

    });

    function calculateSum() {

        var sum = 0;
        //iterate through each textboxes and add the values
        jQuery("#tab-5 input.text.long-field").each(function() {

            //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0 && this.id !== "customfield_11071") {
                sum += parseFloat(this.value);
            }

        });
        //.toFixed() method will roundoff the final sum to 2 decimal places
        jQuery("#customfield_11071").val(sum.toFixed(2));
    }

HTML

  <div class="tabs-pane active-pane" id="tab-5">
    <div class="field-group">
      <label for="customfield_12370">
        Test Case Estimate
      </label>
      <input class="text long-field" id="customfield_12370" name="customfield_12370" type="text" value="">
      <div class="description">
        Will hold all QA estimates for Test Case preparation/creation efforts.
      </div>
    </div>
    <div class="field-group">
      <label for="customfield_12371">
        Test Analysis Estimate
      </label>
      <input class="text long-field" id="customfield_12371" name="customfield_12371" type="text" value="">
      <div class="description">
        Will hold all QA estimates for testing analysis efforts.
      </div>
    </div>
    <div class="field-group">
      <label for="customfield_11071">
        QA Estimate Total
      </label>
      <input class="text long-field" id="customfield_11071" name="customfield_11071" type="text" value="">
      <div class="description">
        Estimated LOE in Hours
      </div>
    </div>
  </div>

UPDATE:或者,也许我可以将特定的id集合填充到数组中并将其传递给each()?

1 个答案:

答案 0 :(得分:0)

您的脚本可以正常工作。见http://jsfiddle.net/jEEKL/。如果您使用此jQuery("#tab-5 input.text.long-field") jQuery选择器获取额外字段,请检查您的源是否有重复的标签ID。