Javascript jQuery使用元素数组为each()设定种子
下面的脚本引发错误(未定义customfields)。我是否需要以不同的方式传递元素ID 我正在尝试使用我要计算的表单字段为数组种子。它应该遍历数组中的每个表单字段,并用表单元素的值递增sum变量Javascript jQuery使用元素数组为each()设定种子,javascript,jquery,each,Javascript,Jquery,Each,下面的脚本引发错误(未定义customfields)。我是否需要以不同的方式传递元素ID 我正在尝试使用我要计算的表单字段为数组种子。它应该遍历数组中的每个表单字段,并用表单元素的值递增sum变量 jQuery(document).ready(function(){ jQuery("#customfield_21070").attr('style','width:60px'); jQuery("#customfield_21070").attr('disabled','disa
jQuery(document).ready(function(){
jQuery("#customfield_21070").attr('style','width:60px');
jQuery("#customfield_21070").attr('disabled','disabled');
var customfields = [
'#customfield_11070',
'#customfield_11071',
'#customfield_20071',
'#customfield_20072',
'#customfield_20073',
'#customfield_20074'
];
jQuery(customfields).each(function() {
jQuery(this).attr('style','width:60px');
jQuery(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
jQuery(customfields).each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0 && this.id !== "customfield_21070") {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
jQuery("#customfield_21070").val(sum.toFixed(2));
}
将数组传递给jQuery不会将数组中的条目用作选择器。您必须将选择器作为字符串传递。调用
this.value
时,this
实际上是一个字符串,而不是一个元素。试一试
jQuery(customfields.join(','))
jQuery的.each()
方法用于迭代jQuery对象。您应该使用一个简单的for
循环来迭代您的数组–无论如何,它比使用jQuery方法快得多
for(var i=0, len=customfields.length; i<len; i++) {
console.log(customfields[i]);
}
for(var i=0,len=customfields.length;i使用
但是,它会将其视为一个字符串数组,然后他会在每个字符串中正确地选择它们。@KevinB在第一个中。我认为每个字符串都是巧合,但在第二个中不是。我认为您的答案是有意义的。Console.log正在工作。现在我只需要让calculate函数工作>
$.each(customfields, function (index, value) {
$(value).attr('style', 'width:60px'); // OR $(value).width(60);
$(value).keyup(function () {
calculateSum();
});
});