Некорректная работа теста. Подскажите, где я ошиблась.

22 июня, 11:52 Учеба 4036 0

Здравствуйте! Я пока ещё новичок в программировании (frontend-pазработка), поэтому прошу не судить меня слишком строго. Заранее благодарю.

Написала простой тест с помощью HTML/Css/JS. Без подключения библиотек и фреймворков. Делала согласно этому примеру https://mirjs.uz/prostaya-viktorina-s-javascript/ . В своём коде пример видоизменила, то есть сделала тест объектом. JS не выводит ошибок в консоли, но на экране я вижу только голубой фон. Подскажите пожалуйста, как можно исправить положение.

Вот мой код.

Перед объектом есть еще массив вопросов с ответами

JS:
function testObject(options){
    this.container = options['container'];//блок-контейнер hWrap
    this.arrQuestions = options['arrQuestions'];//массив вопросов hQn
    //this.arrResults = options['arrResults'];//массив результатов hAns
    this.questionWrapper = null;//флаги для оценки текущего вопроса
    this.resultWrapper = null;
    this.now = 0;//текущий вопрос
    this.score = 0;//текущий счёт

    function Constructor(object){
    let callFuncObj = object.init();
    object.container = object.createElement(callFuncObj);
    object.currentQuestion();
    object.select();
    object.reset();
    }

    this.init = function(){//созданиие элементов HTML
    this.container = document.getElementById('question');
    this.questionWrapper = document.createElement('div');
    this.questionWrapper.id = 'quizId';
    this.container.appendChild(this.questionWrapper);
    this.resultWrapper = document.createElement('div');
    this.resultWrapper.id = 'resultId';
    this.container.appendChild(this.resultWrapper);
    };
    window.addEventListener("load", this.init);

    this.currentQuestion = function(){//вывод текущего вопроса
    this.questionWrapper.innerHTML = this.arrQuestions[this.now];
    this.resultWrapper.innerHTML = '';
    for(let i in this.arrQuestions[this.now]){
        let radioBtn = document.createElement('input');
        radioBtn.type = 'radio';
        radioBtn.name = 'selectBtn';
        radioBtn.id = 'btnId' + i;
        this.container.appendChild(radioBtn);
        let label = document.createElement('label');
        label.innerHTML = this.questionWrapper[this.now];
        label.setAttribute('for', 'btnId' + i);
        label.dataset.idx = i;
        label.addEventListener('click', () => {this.select(label);});
        this.arrQuestions.appendChild(label);
    }

    this.select = function(option){//ф-я для выбора варианта ответа (всего их 4)
        let allQuestions = this.arrQuestions.querySelector('label');
        for(let label of allQuestions){
            label.removeEventListener('click', this.select);//удаляем обработчик события клик
            let correct = option.dataset.id = this.arrQuestions[this.now];//сохраняем в массиве вопросов id (в кач-ве параметра)
            if(correct){
                this.score++;
                option.classList.add(correct);
            }else{
                option.classList.add('wrong');
            }
            this.now++;
            setTimeout(() => {
                if(this.now > this.arrQuestions.length){
                    this.currentQuestion();
                }else{
                    this.container.innerHTML = `Вы ответили на ${this.score} из ${this.arrQuestions.length} правильно`;
                    this.resultWrapper.innerHTML = '';
                }
            },1000)
        }
        this.reset = function(){//ф-я для перезапуска викторины
           this.now = 0;
           this.score = 0;
           this.currentQuestion();
        }
    }
    };

    Constructor(this);
}

Стили:


.question{
    max-width:600px;
    margin: 0 auto;
    /*рекомендуется устанавливать высоту когда у вас есть контент ниже блока question
    так страница не будет "прыгать"
    height:250px;*/
}
.quizId{
    padding:20px;
    background:#4c93ba;
    color:#ffffff;
    font-size:24px;
    border-radius:10px;
}

.resultId{
    margin:10px 0;
    display:grid;
    grid-template-columns:auto auto;
    grid-gap:10px;
}
.resultId input[type = radio]{
    display: none;
}
.resultId label{
    background:#fafafa;
    border:1px solid #eee;
    border-radius:10px;
    padding:10px;
    font-size:20px;
    cursor:pointer;
    text-align:center;
}
.resultId label.correct{
    background:#d8ffc4;
    border:1px solid #60a03f;
}
.resultId label.wrong{
    background:#ffe8e8;
    border:1px solid #c78181;
}
html,body{
    background:#74b6db;
    font-family: arial, sans-serif;
}
 

А вот такой результат получается https://prnt.sc/-WpFhp8bReVH

0 комментариев
Сортировка:
Добавить комментарий

IT Новости

Смотреть все