У меня возникли проблемы с тем, как правильно вернуть значение в пределах одной функции и передать ее другому. Переменная randomQuestion, и я не могу заставить ее появляться в функциях как целое число. Идея состоит в том, что один и тот же идентификатор вопроса используется в обеих функциях, поэтому, например, во второй функции я могу использовать его для определения того, какой вопрос задан, и найти правильный ответ, чтобы он соответствовал ему.Возвращаемые значения и область переменных в 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;
}
}
используя другое имя переменной, чем 'randomQuestion' поможет – sam