获取错误[objecthtmlcollection]

Getting error [object HTMLCollection]

本文关键字:objecthtmlcollection 取错误 获取      更新时间:2023-09-26

我在javascript中做一个简单的测试有问题。这是一个简单的例子。每个问题的div id在html代码中递增。

HTML

<form action="#">
    <div id="q1">
        <label>Q. ABCD</label>
        <label><input type="radio" name="radio1" value="1">A</label>
        <label><input type="radio" name="radio1" value="2">B</label>
        <label><input type="radio" name="radio1" value="3">C</label>
        <label><input type="radio" name="radio1" value="4">D</label>
    </div>
    ....
    ....
    <input type="button" value="Click to Submit" onClick="result();">
</form>

JS(10道题)

function result() {
    var answer = new Array();
    for(var i=1; i<11 ; i++) {
        if(document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
            answer[i] = document.getElementById("q" + i).getElementsByTagName("input");
        }
        else {
            answer[i] = 0;
        }
    }
    console.log(answer);
}

我得到一个错误[对象HTMLCollection]每次我提交的代码。我应该如何做到这一点,以便我可以得到数组中给出的每个答案的值,如果有人没有回答任何问题,数组必须在其位置得到0值,而不是未定义。我需要一个纯JS和HTML的解决方案。

试试这个

function result() {
    var answer = new Array();
    // there is no answer 0
    answer[0] = 'unused';
    for(var i=1; i<11 ; i++) {
        // check if the id exists first
        var container = document.getElementById("q" + i);
        if(container) {
            // get the selected radio checkbox
            var input = container.querySelector("input:checked");
            // if there's one selected, save it's value
            if(input) {
                answer[i] = input.value;
            }
            else {
                answer[i] = 0;
            }
        }
    }
    console.log(answer);
}

一个工作小提琴- http://jsfiddle.net/dtpLjru1/

在您的代码中,您试图通过使用getElementByTagName()来存储HTML集合。此方法将返回所有名称为"input"的标签,因此根据上面的代码,总共有4个标签。

相反,您可以像下面这样修改代码:

假设您希望在选中单选按钮时存储"1"。其他0

function result() {
        var answer = new Array();
        for (var i = 1; i <= 4 ; i++) {
            if (document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
                answer[i] = document.getElementById("q" + i).checked ? 1 : 0;
            }
            else {
                answer[i] = 0;
            }
        }
        console.log(answer);
    }

还没有测试过代码,我们这样做怎么样?

function result() {
    var answer = new Array();
    for(i=1; i<11 ; i++) {
        if(document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
            document.write( document.getElementById("q" + i).getElementsByTagName("input") );
        }
        else {
            document.write(0);
        }
    }
}
相关文章:
  • 没有找到相关文章