JavaScript getElementById你可以在括号内获得创意吗?

时间:2015-08-12 18:12:19

标签: javascript html

我正在开展一个小项目,以提高我的技能,而且我目前处于停滞状态。

如果你在getElementById看下面的代码(没有工作),在括号内我试图获取字大小并将其与变量值组合(值包含用户的选项值)选择)。例如,它将是getElementById(size28 [i]),但当然会发生28次更改。

所以我想我的问题是,无论如何我能做到吗?

var allSizes = new Array(28,30,32);
var size28 = new Array("tgp_0", "tgp_1", "tgp_2", "tgp_3");
var size30 = new Array("tgp_0", "tgp_1", "tgp_2");
var size32 = new Array("tgp_0", "tgp_1", "tgp_2");

var index = document.rightAngle.ddHP.selectedIndex;
var value = document.rightAngle.ddHP.options[index].value;

for (var i=0; i<allSizes.length; i++) {
    if (value == allSizes[i]) {
        var s = "size";
        for (var j=0; j<6; j++) {
            document.getElementById(s+value+[j]).style.display = 'block';
        }
    }
}

然后是HTML部分:

<select name="ddHP">
 <option value="28">28</option>
 <option value="30">30</option>
 <option value="32">32</option>
</select>

<div id="tgp_0" class="idiv"><h1>Item 0</h1></div>
<div id="tgp_1" class="idiv"><h1>Item 1</h1></div>  
<div id="tgp_2" class="idiv"><h1>Item 2</h1></div>
<div id="tgp_3" class="idiv"><h1>Item 3</h1></div>  

2 个答案:

答案 0 :(得分:2)

你不能将变量的名称作为字符串引用(好吧,你可以使用一个名为eval的东西,或者我想通过做window["nameOfVariable"],但那真的很混乱,不值得推荐所有)。我建议将所有大小的数组放在另一个数组中,或者更好的是一个对象文字。

像这样:

var sizes = {
  "28": new Array("tgp_0", "tgp_1", "tgp_2", "tgp_3"),
  "30": new Array("tgp_0", "tgp_1", "tgp_2"),
  "32": new Array("tgp_0", "tgp_1", "tgp_2")
};

现在,以编程方式引用任何特定大小的数组要容易得多。您无需获取名为“size28”的确切变量,而只需引用sizes["28"](如果您愿意,可以将这些键更改为整数而不是字符串;实际上并不重要。)

现在,您只需检查value对象中是否存在sizes,如果确实存在,则执行CSS修改操作:

var index = document.rightAngle.ddHP.selectedIndex;
var value = document.rightAngle.ddHP.options[index].value;

// check if this value exists in the sizes array
// (edit: actually, this check is kind of redundant since you know the <select> tag only contains options "28", "30", and "32". you don't need this IF statement)
if (typeof sizes[value] !== 'undefined') {
    for (var j=0; j<6; j++) {
        document.getElementById(sizes[value][j]).style.display = 'block';
    }
}

答案 1 :(得分:0)

将这些变量存储在对象中,您可以使用括号/字符串表示法来提取所需内容:

var allSizes = new Array(28,30,32);
var sizeGroups = {
    size28 : ["tgp_0", "tgp_1", "tgp_2", "tgp_3"],
    size30 : ["tgp_0", "tgp_1", "tgp_2"],
    size32 : ["tgp_0", "tgp_1", "tgp_2"]
}

var index = document.rightAngle.ddHP.selectedIndex;
var value = document.rightAngle.ddHP.options[index].value;

for (var i=0; i<allSizes.length; i++) {
    if (value == allSizes[i]) {
        var s = "size";
        for (var j=0; j<6; j++) {
            document.getElementById(sizeGroups[s+value][j]).style.display = 'block';
        }
    }
}