gpt4 book ai didi

javascript - jQuery 用元素数组为each() 播种

转载 作者:行者123 更新时间:2023-11-28 09:12:54 31 4
gpt4 key购买 nike

下面的脚本抛出错误(自定义字段未定义)。我需要以不同的方式传递元素 ID 吗?

我正在尝试使用我要计算的表单字段来为数组播种。它应该迭代数组中的每个表单字段,并用表单元素的值递增 sum 变量。

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 的 .each() 方法旨在迭代 jQuery 对象。您应该使用简单的 for 循环来迭代数组 - 无论如何,它比使用 jQuery .each() 方法要快得多。

for(var i=0, len=customfields.length; i<len; i++) {
console.log(customfields[i]);
}

有关性能声明的证明:http://jsperf.com/jquery-each-vs-for-loop

关于javascript - jQuery 用元素数组为each() 播种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16090824/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com