简体   繁体   English

如何在 getElementById 中使用数组?

[英]How to use array in getElementById?

I am working on a project where I need to use array values in the getElementById() in javascript.我正在做一个项目,我需要在 javascript 的getElementById()中使用数组值。 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"];

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");当我硬编码像document.getElementById("examState1");这样的值时,代码工作得很好but not when i use the array.但不是当我使用数组时。

str1 is an integer that I pass from a jsp file below: str1 是一个 integer,我从下面的 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.先感谢您。

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 后调用此 function,尝试在底部添加脚本

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.在想知道为什么docuemnt.getElementById之前,您应该首先确保您传入的内容是您所期望的。 Use alert , or with Firebug console.log to output the value you are passing in:使用alert ,或使用 Firebug console.log到 output 您传入的值:

alert(examStateArr[str1 - 1]);
alert(examStateArr[0]);
alert(examStateArr);

if it works in the hard coded state then your problem must be in the str1-1 part of the code.如果它在硬编码的 state 中工作,那么您的问题一定出在代码的 str1-1 部分。

You haven't provided info on what str1 is.您尚未提供有关 str1 是什么的信息。 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-1) (带括号)......这可能会清除它并确保 str1 是一个代表您的数组索引 + 1 的值(可能是 alert(str1) 在您调用之前查看它实际上是,而不是你认为的那样)。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM