javascript - Javascript 中的返回值和变量范围

标签 javascript variables scope

我在弄清楚如何在一个函数中正确返回一个值并将其传递给另一个函数时遇到一些麻烦。变量是 randomQuestion,我无法让它以整数形式出现在函数中。这个想法是在两个函数中使用相同的问题 ID,因此例如在第二个函数中,我可以使用它来确定提出的问题,并找到正确的答案以将其与用户输入相匹配。

$('#quiz').on('click', beginQuiz);
$('#giveanswer').on('click', nextQuestion);

var randomQuestion = Math.floor(Math.random() * questions.length);

function beginQuiz(randomQuestion) {

    $("#questions tbody tr").remove();
    document.getElementById("questions").deleteTHead();

    //Get the JSON data from our HTML and convert it to a JavaScript object
    //In the real world, this data will likely be retrieved  from the server via an AJAX request
    var questions = JSON.parse(document.getElementById('questions-json').innerHTML);



    console.log(randomQuestion);

    var quizQuestion = questions[randomQuestion];


    var tblRow = '<tr>' + '<td>' + quizQuestion.q_text + '</td>' + '</tr>'
        //Add our table row to the 'questions' <table>
    $(tblRow).appendTo('#questions tbody');

    document.getElementById('answers').style.display = 'block';
    document.getElementById('answerlabel1').innerHTML = quizQuestion.q_options_1;
    document.getElementById('answerlabel2').innerHTML = quizQuestion.q_options_2;
    document.getElementById('answerlabel3').innerHTML = quizQuestion.q_options_3;
    document.getElementById('answerlabel4').innerHTML = quizQuestion.q_options_4;

    return randomQuestion;
}

function nextQuestion(randomQuestion) {

    console.log(randomQuestion);
    //Get the JSON data from our HTML and convert it to a JavaScript object
    //In the real world, this data will likely be retrieved  from the server via an AJAX request
    var questions = JSON.parse(document.getElementById('questions-json').innerHTML);
    var score = 0;
    var playeranswer = $('input:radio[name=answer]:checked').val();
    var correctanswer = questions[randomQuestion].q_correct_option;

    if (playeranswer == questions.q_correct_option) {
        score++
        document.getElementById('score').innerHTML = score;
    }
}

最佳答案

从两个函数声明中删除 randomQuestion 参数,因为它是全局的。正如所写,您的两个函数都会查看自己的本地 raqndomQuestion 变量,该变量未定义。

关于javascript - Javascript 中的返回值和变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32993285/

相关文章:

创建变化的变量

javascript - 从内联 html 页面访问外部 JS 变量?

vba - 将工作簿声明为全局变量

javascript - 如何延迟()qtip()加载工具提示

javascript - document.cookie 只存储第一个键值对?

javascript - 将 JSX 元素呈现为多层金字塔

c++ - 在没有new关键字的情况下创建的c++中结构对象的范围

javascript - Angular 异步加载变量未在 View 中更新

javascript - Javascript 中的变量赋值顺序是什么?

javascript - 从事件外部调用事件内部的函数