Javascript getElementById(array[x])?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2178733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:07:00  来源:igfitidea点击:

getElementById(array[x])?

javascript

提问by Strawberry

I'm trying to put an array in to getElementById for a loop purpose. It seems to be not working, how can I do this?

我正在尝试将一个数组放入 getElementById 以用于循环目的。它似乎不起作用,我该怎么做?

Edit: Sorry folks It says undefined.

编辑:对不起,伙计们它说未定义。

    var lol=new Array( "test", "test2" );

var x = 0;
while( x == 4 ) {
    number = parseInt(document.getElementById(lol[x]).value);
    x++;
}

And i have inputs id named test and test2.

我有名为 test 和 test2 的输入 ID。

回答by Aaron

Your while loop only works if x==4. Change this to:

您的 while 循环仅在 x==4 时有效。将此更改为:

while(x < lol.length)

To loop through all the elements in the array. Better yet, this will condense your loop:

遍历数组中的所有元素。更好的是,这将压缩您的循环:

var lol=new Array( "test", "test2" );
for( var x = 0; x < lol.length; x++ ) {
    number = parseInt(document.getElementById(lol[x]).value);
}

回答by cjstehno

Try taking your array out of the quotes...

尝试从引号中取出数组...

document.getElementById(lol[x]).value

The quotes turn it into a static string "lol[x]", when you want the value of the lol array at x index.

当您想要 x 索引处的 lol 数组的值时,引号会将其转换为静态字符串“lol[x]”。

This replaces my earlier, less informed answer.

这取代了我之前的、不太了解的答案。

Hope this helps

希望这可以帮助

回答by Anonymous

You say you have number = parseInt(document.getElementById("lol[x]").value);

你说你有 number = parseInt(document.getElementById("lol[x]").value);

  1. "lol[x]"is a string with that literal value, not the value that lolholds at index x. Use getElementById(lol[x])

  2. parseIntmay do unexpected things when you don't pass a radix. Use something like parseInt(document.getElementById(lol[x]).value, 10)

  1. "lol[x]"是具有该字面值的字符串,而不是lol保存在 index 处的值x。用getElementById(lol[x])

  2. parseInt不传递基数时可能会做意想不到的事情。使用类似的东西parseInt(document.getElementById(lol[x]).value, 10)

Finally, you aren't checking whether the element exists. Do something like:

最后,您不是在检查元素是否存在。做类似的事情:

var element = document.getElementById(lol[x]);
if (element) {
  number = parseInt(element.value, 10);
} else {
  // handle error or throw exception
}