JavaScript,如何将变量解析为命令?

时间:2012-07-19 14:44:07

标签: javascript parsing variables command

我要做的是在for()中启用多个复选框。现在它看起来像这样,但从我所学到的,你不能从这样的变量运行命令,我无法运行,(例如)cab_type_value = "whatever"。我也无法运行road_load_enabled;它只是不起作用。有谁可以实现这个目标?如何解析J中的var document.MyForm.InputName.disabled

for( var j=1; j<=14; j++ ) {
    var cab_type_value = "document.exe_mode_form.cab_type" + j + ".value";
    var cab_type_checked = "document.exe_mode_form.cab_type" + j + ".checked == 1";

    for( var i=1; i<=document.exe_mode_form.road_load_number.value; i++ ) {
        var road_load_value = "document.exe_mode_form.load" + i + ".value";
        var road_load_enabled = "document.exe_mode_form.load" + i + ".disabled = false";
        var road_load_disabled = "document.exe_mode_form.load" + i + ".disabled = true";
        var rld_db = "document.exe_mode_form.a" + i + "_a1.value";

        if ( cab_type_checked ) {
            if ( test == 1 ) {
                if(road_load_disabled) {
                    alert("road_load_disabled");
                    road_load_enabled;
                }
                test = 2;
            }

            if(cab_type_value == rld_db) {
                if(olof == 1) {
                    alert("cab_type_value  == rld_db");
                    olof = 2;
                }

                road_load_enabled;
            }
        }
    }
}

此外,这部分不起作用:

if(cab_type_value == rld_db) {
    if(olof == 1){
        alert("cab_type_value  == rld_db");
        olof = 2;
    }

    road_load_enabled;
}

我已检查过,cab_type_value的值与rld_db相同。

1 个答案:

答案 0 :(得分:1)

尝试更改这些行:

var cab_type_value = "document.exe_mode_form.cab_type" + j + ".value";

为:

var cab_type_value = document.exe_mode_form['cab_type' + j].value;

同样的逻辑适用于函数调用:

someVariable = 'alert';
window[someVariable]('Foo!');//alerts foo

如果您的函数未在全局范围内声明,则可以将window替换为任何名称空间对象:foobarObject.orEven.nestedOnes[someVariable]();
最后,因为我个人厌恶window关键字(它是一个循环引用),您只需在常规函数调用或全局范围内选择使用this['alert']('foo');即可。 this指向其被称为上下文,在这些情况下是全局对象