同时在数组中添加一个元素,在javascript中给出错误

时间:2016-12-09 11:29:54

标签: javascript html

我有15个问题测验。它为4个问题工作,同时再添加一个问题给出错误(不显示任何内容)。添加15个问题需要改变什么。某处数组大小修正错误。

    <script>
        var pos = 0, test, test_status, question, choice, choices, chA, chB, chC,chD, correct = 0;
var questions = [
    ["q1", "Internet Only Thing", "Inter Online Technology", "Internet of Things", "International Online Techn", "C"],
    ["q2", "Computer", "Object", "Mobile", "Tab", "B"],
    ["q3", "a", "b", "xyz","z", "A"],
    ["q4", "hfjh", "fsafs", "fasf", "faas", "C"]
    ["q5", "fasfa", "fasfa", "fasfd","fas", "A"]


    //   ["...", "...", "...", "...", "B"]
     //  ["q5", "...", "...", "...", "...", "C"]
];
function _(x){
    return document.getElementById(x);
}
function renderQuestion(){
    test = _("test");
    if(pos >= questions.length){
        test.innerHTML = "<h2>You gave  "+correct+" answers out of "+questions.length+" questions </h2>";
        _("test_status").innerHTML = "quiz 1 Completed";
        pos = 0;
        correct = 0;
        return false;
    }
    _("test_status").innerHTML = "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Question " + (pos + 1) + " of " + questions.length;
    question = questions[pos][0];
    chA = questions[pos][1];
    chB = questions[pos][2];
    chC = questions[pos][3];
    chD = questions[pos][4];

    test.innerHTML = "<h3>"+question+"</h3>";
    test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
    test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
    test.innerHTML += "<input type='radio' name='choices' value='C'> " + chC + "<br>";
    test.innerHTML += "<input type='radio' name='choices' value='D'> " + chD + "<br><br>";
    test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}
function checkAnswer(){
    choices = document.getElementsByName("choices");
    for(var i=0; i<choices.length; i++){
        if(choices[i].checked){
            choice = choices[i].value;
        }
    }
    if(choice == questions[pos][5]){
        correct++;
    }
    pos++;
    renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
    </script>

2 个答案:

答案 0 :(得分:0)

嘿,我查看了你的代码

在您的代码中,从1到4的问题有4个选项和1个答案,而在第5个问题中,您只添加了3个选项和1个答案。

可能有问题请检查。

答案 1 :(得分:0)

我认为你在问题数组中缺少一些逗号。 替换为:

var questions = [
        ["q1", "Internet Only Thing", "Inter Online Technology", "Internet of Things", "International Online Techn", "C"],
        ["q2", "Computer", "Object", "Mobile", "Tab", "B"],
        ["q3", "a", "b", "xyz","z", "A"],
        ["q4", "hfjh", "fsafs", "fasf", "faas", "C"],
        ["q5", "fasfa", "fasfa", "fasfd", "A"],
        ["...", "...", "...", "...", "B"],
        ["q5", "...", "...", "...", "...", "C"]
    ];

如果这对你有用,请告诉我。尝试过并且似乎有效。