如何在getElementById中使用数组? [英] How to use array in getElementById?

查看:62
本文介绍了如何在getElementById中使用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,我需要在JavaScript的 getElementById()中使用数组值.我尝试了各种方法,但是代码无法正常工作.请帮助我.

I am working on a project where I need to use array values in the getElementById() in javascript. I tried various things, but the code isn't working. Please help me.

我有一个这样的值数组:

I have an array of values like this:

 var examStateArr=["examState1","examState2","examState3","examState4","examState5","examState6","examState7"];

并且我在 getElementById()中将其用作:

document.getElementById(examStateArr[str1-1]).value.innerHTML=xmlHttp.responseText

但这不起作用.

当我对诸如 document.getElementById("examState1"); 之类的值进行硬编码时,代码工作得很好,但是当我使用数组时却不能.

The code works just fine when I hard code values like document.getElementById("examState1"); but not when i use the array.

str1是我从下面的jsp文件传递的整数:

str1 is an integer that I pass from a jsp file below:

<%for (int j = 1; j < 8; j++) {%>
<tr>
<select  name='examCountry<%= j%>' onchange=showExamState(<%= j%>,this.value);>  
<option value="none" selected="selected">SELECT</option>
<% for (i = 0; i < countrySize; i++) {%>
<% country = (String) countryArr.get(i);%>
<option  value=<%= country%>><%= country%></option>
<% }%>
</select> 


</td>
<td id='examState<%= j%>'>
<select name='examState<%= j%>'>  
<option value='none'>Select</option>
</select>
</td>

请纠正我的错误.

谢谢.

推荐答案

var examStateArr = ["examState1", "examState2", "examState3", "examState4", "examState5", "examState6"];

for (var i = 0; i < examStateArr.length; i++) {
    document.getElementById(examStateArr[i]).innerHTML = xmlHttp.responseText   
}

错误地完成一项操作

document.getElementById('').value.innerHTML   -- is wrong
document.getElementById('').innerHTML         -- is correct

编辑2

确保在加载DOM之后调用此函数,请尝试在底部添加脚本

make sure you call this function after DOM is loaded, try adding your script at the bottom

这篇关于如何在getElementById中使用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆