Javascript 如何在 getElementById 中使用数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6627255/
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
How to use array in getElementById?
提问by Sathya
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.
我正在开发一个需要getElementById()
在 javascript 中使用数组值的项目。我尝试了各种方法,但代码不起作用。请帮我。
I have an array of values like this:
我有一个这样的值数组:
var examStateArr=["examState1","examState2","examState3","examState4","examState5","examState6","examState7"];
and i use it in getElementById()
as:
我用它getElementById()
作为:
document.getElementById(examStateArr[str1-1]).value.innerHTML=xmlHttp.responseText
But this doesnt work.
但这不起作用。
The code works just fine when I hard code values like document.getElementById("examState1");
but not when i use the array.
当我对值进行硬编码时,代码工作得很好,document.getElementById("examState1");
但当我使用数组时则不然。
str1 is an integer that I pass from a jsp file below:
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>
Please correct my mistake.
请纠正我的错误。
Thank you in advance.
先感谢您。
回答by Praveen Prasad
var examStateArr = ["examState1", "examState2", "examState3", "examState4", "examState5", "examState6"];
for (var i = 0; i < examStateArr.length; i++) {
document.getElementById(examStateArr[i]).innerHTML = xmlHttp.responseText
}
Mistake one done by you
你做的一个错误
document.getElementById('').value.innerHTML -- is wrong
document.getElementById('').innerHTML -- is correct
Edit 2
编辑 2
make sure you call this function after DOM is loaded, try adding your script at the bottom
确保在加载 DOM 后调用此函数,尝试在底部添加脚本
回答by Nicole
You haven't shown us what str1
is but it must be the problem.
您还没有向我们展示str1
是什么,但这一定是问题所在。
For example, try:
例如,尝试:
document.getElementById(examStateArr[0])
And that should work fine. Array access is zero-based and you have six elements, so the valid values for [n]
are 0-5.
这应该可以正常工作。数组访问是从零开始,你有六个要素,所以对于有效的值[n]
是0-5。
It's also possible your array doesn't contain what you think it contains. Before wondering why docuemnt.getElementById
isn't working, you should first make sure that what you are passing in is what you expected. Use alert
, or with Firebug console.log
to output the value you are passing in:
您的数组也可能不包含您认为它包含的内容。在想知道为什么docuemnt.getElementById
不起作用之前,您应该首先确保您传递的内容是您所期望的。使用alert
, 或与 Firebugconsole.log
一起输出您传入的值:
alert(examStateArr[str1 - 1]);
alert(examStateArr[0]);
alert(examStateArr);
回答by Yevgeny Simkin
if it works in the hard coded state then your problem must be in the str1-1 part of the code.
如果它在硬编码状态下工作,那么您的问题必须出在代码的 str1-1 部分。
You haven't provided info on what str1 is. Whatever it is, try (str1-1) (with parens)... that might clear it up and make sure str1 is a value that represents your array index + 1 (maybe alert(str1) prior to your call to see what it actually is, rather than what you think it is).
您尚未提供有关 str1 是什么的信息。不管它是什么,尝试 (str1-1) (带括号)...这可能会清除它并确保 str1 是一个代表您的数组索引 + 1 的值(可能在您调用之前使用 alert(str1) 以查看它是什么实际上是,而不是您认为的那样)。
回答by Hubert Lohmaier
Yes - this is an old entry but still an up to date topic. So I stumbled over it as well when I was looking for a solution for the following problem: The array does not exist at the beginning (as in the example above) but will be generated dynamically via PHP inside a HTML form.
是的 - 这是一个旧条目,但仍然是一个最新的主题。因此,当我为以下问题寻找解决方案时,我也偶然发现了它:数组在开始时不存在(如上例所示),但会通过 HTML 表单内的 PHP 动态生成。
My problem was that the text lines come in with ids (or names) like for example "text[0], text[1]" and I was neither able to write getElementById("text[0]")neither getElementById("text"[0]).
我的问题是文本行带有 id(或名称),例如“text[0], text[1]”,我既不能写getElementById("text[0]")也不能写getElementById("text "[0])。
It took me some time to find a solution so I wrote some example code that works for this problem. Maybe someone finds it helpful ...
我花了一些时间来找到解决方案,所以我写了一些适用于这个问题的示例代码。也许有人觉得它有帮助......
<!DOCTYPE html>
<html>
<head>
</head>
<script>
function getTotal(i) {
console.log("Line clicked: " + i);
var substr = "";
var radio_test = "myRadio"; // !! Name may not be at the same length as "value_test" in this example
var value_test = "myVal";
var sum_id = document.getElementById("aim");
var all = document.getElementsByTagName("*");
var values = [];
var status = [];
console.log("------------------------------------------------");
// STEP 1: Check radio elements if on/off and save their status and also their corresponding value fields
for (var i=0, max=all.length; i < max; i++) {
if (all[i].id != "") {
console.log("Find element " + all[i].id);
substr = all[i].id.substring(0, 7);
if (substr == radio_test) {
console.log("=> Radio element (" + all[i].id + ") BUTTON-NO (" + all[i].value + ") STATUS (" + + all[i].checked + ")");
if (all[i].value == 1) {
if (all[i].checked == true) {
console.log("ON");
status.push(1);
}
else {
console.log("OFF");
status.push(0);
}
}
} else {
substr = all[i].id.substring(0, 5);
if (substr == value_test) {
console.log("Value element - NAME " + all[i].id + " VAL " + all[i].value);
values.push(all[i].value);
} else
console.log("Another element we do not need at the moment");
}
}
}
// STEP 2: iterate through saved values and sum them up if radio button status was checked
console.log("------------------------------------------------");
var sum=0;
for (i=0; i<=status.length; i++) {
if (status[i] > 0)
sum += parseInt(values[i]);
}
sum_id.value = sum;
}
</script>
<body>
<br>USE JAVASCRIPT TO SUM UP VALUES FROM ALL CHECKED LINES THAT WERE CREATED DYNAMICALLY
<br><br>
<?php
// Total sum of all checked lines
echo "<div style='clear: both; padding: 5px; border-color: red; border-style: solid; margin-top: 2px;'>";
echo "SUM <input id='aim' name='aim' type='text'>";
echo "</div>";
echo "<br><br>";
// Create some lines dynamically (and fill them with random values for testing purpose)
for ($i=0; $i<10; $i++) {
echo "<div style='clear: both; padding: 5px; border-color: black; border-style: solid; margin-top: 2px;'>";
echo "Line $i: <input type='text' id='myVal[".$i."]' name='myVal[".$i."]' value='".random_int(1, 100)."' >";
echo " ON <input type='radio' id='myRadio[".$i."]' name='myRadio[".$i."]' value='1' onchange='getTotal($i)'>";
echo " OFF <input checked type='radio' id='myRadio[".$i."]' name='myRadio[".$i."]' value='2' onchange='getTotal($i)'>";
echo "</div>";
}
?>
</body>
</html>