2015-10-07 26 views
0

在解决如何在一个函数内正确返回值并将其传递给另一个函数时遇到了一些麻烦。该变量是randomQuestion,我不能让它作为一个整数出现在函数中。这个想法是,两个函数都使用相同的问题ID,所以例如在第二个函数中,我可以使用它来确定问题是什么问题,并找到正确的答案以使其与用户输入相匹配。Javascript中的返回值和变量范围

$('#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; 
    } 
} 
+0

使用不同的变量名称比'randomQuestion'将有助于 – sam

回答

2

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

+0

啊我看,这是有道理的。如果我想在第二个函数中使用全局变量,但是它在本地发生了变化,那么随着全局变量调用该函数时它会被覆盖吗? – user3052485

+0

如果更改函数内部的全局变量,它将在全局变化,所以下一个函数将使用更改后的值。 – Shilly