如何使用 onclick 进行循环前进

How do I make a loop advance using onclick?

本文关键字:循环 onclick 何使用      更新时间:2023-09-26

我一直试图弄清楚这个问题一段时间,但我完全被难住了。

我正在编写一个程序,应该显示一系列基本的多项选择题。您看到一个问题,单击其中一个答案,然后转到下一个问题。

问题是,我不知道如何显示一个问题,然后在用户单击其中一个按钮时显示下一个问题。当我单击按钮时没有任何反应。出了什么问题?

        // progress meter
        var progress = new Array();
        for (var i = 0; i < questions.length; i++) progress.push("0");
        var i = 0;
        display(0);
        // display questions
        function display(i) {
            var prg_string;
            for (var j = 0; j < progress.length; j++) prg_string += progress[j];
            document.write(
                "<div id = 'background'>"
                    + "<div id = 'progress'>" + progress + "</div>"
                    + "<div id = 'title'>-JogNog Test v1-<br></br>" + tower + "</div>"
                    + "<div id = 'question'>" + questions[i].text + "</div>"
                    + "<div id = 'stats'>Level " + level + "/" + total_levels + " Question " + (i + 1) + "/" + questions.length + "</div>"
                + "</div>"
            );
            document.write("<button id = 'answer1' onclick = 'next(questions[i].answers[0].correct)'>" + questions[i].answers[0].text + "</button>");
            if (questions[i].answers.length > 0)
                document.write("<button id = 'answer2' onclick = 'next(questions[i].answers[1].correct)'>" + questions[i].answers[1].text + "</button>");
            if (questions[i].answers.length > 1)
                document.write("<button id = 'answer3' onclick = 'next(questions[i].answers[2].correct)'>" + questions[i].answers[2].text + "</button>");
            if (questions[i].answers.length > 2)
                document.write("<button id = 'answer4' onclick = 'next(questions[i].answers[3].correct)'>" + questions[i].answers[3].text + "</button>");
        }
        // go to next question, marking whether answer was right or wrong
        function next(correct) {
            if(correct) progress[i] = "T";
            else progress[i] = "F";
            i += 1;
            display(i);
        }

我还没有通读你的代码,(你可能想通过只关注处理循环的部分来发布 SSCCE),但我感觉循环不是你想要的。如果您需要自动迭代某些内容,循环非常有用。但实际上,您一次只想显示一个问题。

假设您有独立处理每个问题的方法,最简单的方法就是跟踪用户在做什么问题。 显示该问题。 当用户提交答案时,调用使用计数器呈现问题的任何函数,加一。 确保检查您是否没有到达测验的末尾,以便您不会引用不存在的问题。

下面是一些伪代码:

var questionNumber, questions; //assume these already have values
function printQuestion(questionNumber){ ... }
function nextQuestion(){
    if(questionNumber < questions){
         questionNumber++;
         printQuestion(questionNumber); 
    }
    else{
         showResults();
    }
}

我同意@ngmiceli,循环不是你想要的。您希望显示一个问题,然后创建单击事件处理程序,当用户选择上一个问题的答案时,该处理程序将移至下一个问题。

我继续创建了一个不同的设置来演示。您可以在此处查看演示:

--

js小提琴演示 --

但我会介绍这个过程。首先,我设置一个基本的 HTML 文档:

<body>
    <h1>-Test v1-</h1>
    <h2>Simple Math</h2>
    <div id="container">
        <div><span id="numRight">0</span> of <span id="numQuestions">0</span></div>
        <div id="question"></div>
        <div id="answerswers"></div>
    </div>
</body>

然后,我创建了一个问题array,数组中的每个元素都是一个object。每个问题对象都包含问题本身、一个可能的答案数组和一个指示正确答案的数组索引的"answerswerIdx"属性。

questions = [
    {
        question: 'What is 0 / 6 ?',
        options: ['0','1','2'],
        answerIdx: 0
    },
    {
        question: 'What is 2 + 2 ?',
        options: ['72','4','3.5'],
        answerIdx: 1
    }
]

我还创建了其他一些变量,这些变量指向我要操作的 HTML 元素:

numRight = 0,
numQuestions = 0,
answerDiv = document.getElementById('answers'),
questionDiv = document.getElementById('question'),
numRightSpan = document.getElementById('numRight'),
numQuestionsSpan = document.getElementById('numQuestions');

接下来,我创建了一个"displayQuestion"函数,它将单个问题对象作为参数:

function displayQuestion(q) {  
    // insert the question text into the appropriate HTML element
    questionDiv.innerHTML = q.question;
    // remove any pre-existing answer buttons
    answerDiv.innerHTML = '';
    // for each option in the 'options' array, create a button
    // attach an 'onclick' event handler that will update
    // the question counts and display the next question in the array
    for(i = 0; i < q.options.length; i++) {
        btn = document.createElement('button');
        btn.innerHTML = q.options[i];
        btn.setAttribute('id',i);
        // event handler for each answer button
        btn.onclick = function() {
            var id = parseInt(this.getAttribute('id'),10);
            numQuestionsSpan.innerHTML = ++numQuestions;
            // if this is the right answer, increment numRight
            if(id === q.answerIdx) {
                numRightSpan.innerHTML = ++numRight;
            }
            // if there is another question to be asked, run the function again
            // otherwise, complete the test however you see fit
            if(questions.length) {
                displayQuestion(questions.shift()); 
            } else {
                alert('Done! You got '+numRight+' of '+numQuestions+' right!');
            }                    
        }
        answerDiv.appendChild(btn);        
    }
}

最后,我展示了第一个问题:

displayQuestion(questions.shift());