簡體   English   中英

jQuery使用元素數組播種each()

[英]jQuery seed each() with an array of elements

以下腳本引發錯誤(未定義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));
    }

將數組傳遞給jQuery不會將數組中的條目用作選擇器。 您必須將選擇器作為字符串傳遞。 當您調用this.valuethis實際上是一個字符串而不是一個元素。 嘗試

jQuery(customfields.join(','))

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

使用jQuery.each()嘗試一下

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM