0

好吧,我一直在寻找如何使用循环(for)检查所有对象的属性,但没有找到太多。

我一直在使用 JS 和 jquery 进行注册表单验证,我为每个字段添加了一个带有属性(falsetrue)的对象,只是为了知道字段是否填充不正确。我想检查所有寻找 a 的属性false,如果有,请禁用该按钮。我试图像这样读取对象:

for(var p in flags){ // flags = object
            if(p == false){
                flagStatus = false;
            }
        }
        if(flagStatus )
            $("#subReg").attr("disabled", false);   
        else
            $("#subReg").attr("disabled", true);

我不确定我错过了什么。任何帮助都会很棒,ty。

编辑:

var flags = {nick: false, pass:false, passVer:false, genero:false, pais:false, fechaNac:false, nombre:false, apellido:false, email:false, checkBox:false, captcha:false};
4

1 回答 1

1

You need to get/compare the value, not the key. Try this:

var flags = {key1: true, key2: false, key3: true};
var flagStatus = true;
for (var p in flags){
    if (flags[p] === false) {
        flagStatus = false;
        break;
    }
}
if (flagStatus)
    $("#subReg").attr("disabled", false);   
else
    $("#subReg").attr("disabled", true);

When looping, the p refers to the key in the object, while flags[p] refers to the value.

In my example above, the first p encountered is "key1", and flags[p] is true. Next, p is "key2" and flags[p] is false - so the if statement passes, flagStatus is set to false, and the looping stops.

Also, you could combine the code at the end (after the loop) to be:

$("#subReg").attr("disabled", !flagStatus);

So you dont need the if/else :)

于 2013-05-03T21:38:51.873 回答