jQuery种子each()带有一个元素数组

时间:2013-04-18 18:47:14

标签: javascript jquery each

以下脚本引发错误(未定义customfields)。我需要以不同方式传递元素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));
    }

3 个答案:

答案 0 :(得分:0)

将数组传递给jQuery不会将数组中的条目用作选择器。您必须将选择器作为字符串传递。当您致电this.value时,this实际上是一个字符串,而不是一个元素。尝试

jQuery(customfields.join(','))

答案 1 :(得分:0)

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

答案 2 :(得分:0)

使用jQuery.each()

尝试此操作
$.each(customfields, function (index, value) {
    $(value).attr('style', 'width:60px');  // OR $(value).width(60);
    $(value).keyup(function () {
        calculateSum();
    });
});