开发者

getElementById(array[x])?

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?

Edit: Sorry folks It开发者_如何学Go 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.


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

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);
}


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.

This replaces my earlier, less informed answer.

Hope this helps


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

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

  2. parseInt may do unexpected things when you don't pass a radix. Use something like 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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜