【发布时间】:2013-04-03 23:49:08
【问题描述】:
在下面的脚本中,我需要更改 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>
更新:或者,与其将类字符串传递给 each,也许我可以将特定的 id 集合填充到一个数组中并将其传递给 each()?
【问题讨论】:
-
jQuery(document).ready(function(jQuery){没有意义。ready处理程序被传递给 jQuery 对象,以便您可以按照自己的意愿声明它。让它们相同会破坏这个目的。 -
"..its picking up text input fields matching the class outside of the tab-5 parent..",不,不是!必须有其他事情发生,因为它不会使用该选择器选择#tab-5之外的元素? -
您可以为 jQuery 选择器提供上下文:
$('input:text', '#tab-5')。然后你就可以确定它没有选择它之外的任何东西。 -
似乎按原样工作...jsfiddle.net/jEEKL
-
@adeneo,也许他的 id 重复?