Простой вопрос / варианты, которые не заполняются из файла JSON, когда пользователь выбирает из выпадающего списка

#javascript

#javascript

Вопрос:

Я пытаюсь создать простое приложение, в котором пользователь может выбрать категорию вопросов, на которые он хотел бы ответить.

Я попытался написать несколько функций, в которых файлы JSON загружаются на основе выбора, который они выбирают из выпадающего списка.

Файл JSON загружается, но он не заполняет вопрос и варианты выбора, когда пользователь затем нажимает «Воспроизвести».

Спасибо за помощь!

HTML

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Play!</title>
    <link rel = "stylesheet" href = "assets/css/style.css">
    <link rel = "stylesheet" href = "assets/css/play.css">
</head>
<body>
    <div class="container">
        <div id = "categoriesForm">
          <h1>Pick Your Category</h1>
            <select name = "subjects" id = "categories">
                <option value = "animals">Animals</option>
                <option value = "food">Food</option>
            </select>
        <button id = "submit" class = "playbtn" onclick = "getCategory(event)">Play!</button>
        </div>
    </div>
    <script src = "assets/scripts/main.js"></script>
</body>
</html>
  

Javascript

 //Get the play button
const submit = document.getElementById("submit");

//Get the value for the dropdown and game
const categories = document.getElementById("categories");
const game = document.getElementById("game");
const categoriesForm = document.getElementById("categoriesForm");
let category;

function getCategory(e){
    e.preventDefault();
    switch(categories.value) {
        case "animals":
            category = "animals";
            AnimalAsCategory();
            break;
        case "food":
            category = "food";
            FoodAsCategory();
            break;
    }

    game.classList.remove("hidden");
    categoriesForm.classList.add("hidden");
    
}

const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));
var scoreText = document.getElementById("hud-score");

let questions = [];
let currentQuestion = {};
let acceptingAnswers = false;
let score = 0;
let questionCounter = 0;
let availableQuestions = []

function AnimalAsCategory () {
    fetch("animals.json")
        .then((res) => {
            return res.json();
        })
        .then((loadedQuestions) => {
            questions = loadedQuestions;
            return questions
        })
        .catch((err) => {
            console.error(err);
        })
        
}

function FoodAsCategory() {
    fetch("food.json")
        .then((res) => {
            return res.json();
        })
        .then((loadedQuestions) => {
            questions = loadedQuestions;
            return questions;
        })
        .catch((err) => {
            console.error(err);
        })
}


startGame = () => {
    questionCounter = 0;
    score = 0;
    lives = 3;
    availableQuestions = [...questions];
    getNewQuestion();
}

getNewQuestion = () => {
    if(availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) {
        localStorage.setItem("mostRecentScore". score);
        return window.location.assign("./end.html");
    }

    questionCounter  ;

    const questionIndex = Math.floor(Math.random() * availableQuestions.length);
    currentQuestion = availableQuestions[questionIndex];
    question.innerText = currentQuestion.question;

    choices.forEach((choice) => {
        const number = choice.dataset["number"];
        choice.innerText = currentQuestion["choice"   number]
    });

    availableQuestions.slice(questionIndex, 1);
    acceptingAnswers = true;
};
  

Комментарии:

1. Приятно показать некоторый код. Однако можете ли вы сократить до той части, где у вас есть проблема? Это много кода для чтения, чтобы найти, в чем ваша проблема

2. Извините. Я отредактирую его, чтобы показать части, в которых возникает проблема

3. @Cid это немного помогает?

4. Моя рекомендация состояла бы в том, чтобы позвонить startGame , так как вы им нигде не пользуетесь. Я бы добавил его после questions = loadedQuestions; в обеих функциях.

5. @imvain2 это сработало, большое спасибо!

Ответ №1:

Не похоже, что вы на самом деле startGame куда-либо звоните.

Я бы добавил его в обе функции синтаксического анализа json после загрузки json.

 function AnimalAsCategory () {
    fetch("animals.json")
        .then((res) => {
            return res.json();
        })
        .then((loadedQuestions) => {
            questions = loadedQuestions;
            startGame();
            return questions
        })
        .catch((err) => {
            console.error(err);
        })
        
}

function FoodAsCategory() {
    fetch("food.json")
        .then((res) => {
            return res.json();
        })
        .then((loadedQuestions) => {
            questions = loadedQuestions;
            startGame();
            return questions;
        })
        .catch((err) => {
            console.error(err);
        })
}