我正在做一个项目,我需要在 javascript 的 getElementById()
中使用数组值。
我尝试了各种方法,但代码不起作用。
请帮帮我。
我有一个这样的值数组:
var examStateArr=["examState1","examState2","examState3","examState4","examState5","examState6","examState7"];
我在 getElementById()
中使用它作为:
document.getElementById(examStateArr[str1-1]).value.innerHTML=xmlHttp.responseText
但这不起作用。
当我硬编码像 document.getElementById("examState1");
这样的值时,代码工作得很好,但当我使用数组时却不行。
str1 是我从下面的 jsp 文件中传递的整数:
<%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 后调用此函数,尝试在底部添加脚本
关于javascript - 如何在 getElementById 中使用数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6627255/