增加函数内部全局变量的值.each()

时间:2012-03-06 16:30:43

标签: jquery

我有这段代码:

$(document).ready(function() {

 var MidUpperArmCircumference = 0;
 var TricepsSkinfold = 0;

function checkMethod(method,parameters){
    $('#'+method+'_check').change(function() {
    if (this.checked == true) {
        $.each(parameters, function() {
            $('.'+this).css('color','blue');
            this++;    //HERE IS THE ERROR!
        });
    }
    });
}

var parametersMuscleArea = ['TricepsSkinfold', 'MidUpperArmCircumference'];
checkMethod('MidUpperArmMuscleArea',parametersMuscleArea);
});

如何在TricepsSkinfold函数中增加变量MidUpperArmCircumference$.each

2 个答案:

答案 0 :(得分:2)

this是字符串,而不是对局部变量的引用。您不能通过增加字符串来增加变量。此外,您尝试通过字符串中给出的名称引用本地变量。对于局部变量,这只能通过eval或通过命名空间变量来完成。

这将有效:

var ns = {
    MidUpperArmCircumference: 0,
    TricepsSkinfold: 0
};

function checkMethod(method,parameters){
    $('#'+method+'_check').change(function() {
        if (this.checked == true) {
            $.each(parameters, function() {
                $('.'+this).css('color','blue');
                ns[this]++;    // <-- Fixed.
            });
        }
    });
}

答案 1 :(得分:0)

简单,只需++ 他们

function checkMethod(method,parameters){
    $('#'+method+'_check').change(function() {
    if (this.checked == true) {
        $.each(parameters, function() {
            TricepsSkinfold++;
            MidUpperArmCircumference++;
            ...
            ...
            $('.'+this).css('color','blue'); // That looks wrong as well...
            // as "this" is the current item of the iteration. 
        });
    }
    });
}