Javascript, который работает в Chrome, но ничего больше - PullRequest
0 голосов
/ 30 января 2012

Я работаю над этим листом проблем с добавлением, и он работает и работает в Chrome, но кнопка «Следующий вопрос» больше не работает.Это моя первая программа на Javascript.Я проверил его через валидатор и получил 1 ошибку, но комментирование этой строки, похоже, не помогает.

Вот весь раздел Javascript:

 <script type="text/javascript">

var questionTop = new Array(); //Array to store the top random number of questions
var questionBot = new Array(); //Array to store the bottom random number of questions
var answers = new Array(); //Array to store the answers the user enters
var correct = new Array(); //Array to store the correct answers
var questionMarker = 0; //Loop counter for number of times through
var correctAnswers = 0; //Counter for number of correct answers

function startQuiz() {
    questionMarker = 0;  //Function starts the quiz and resets the form
    correctAnswers = 0;  //so that the first random numbers show up and hides the start button
    document.getElementById('startButton').style.visibility='hidden';
    document.getElementById('nextQuestion').style.visibility='visible';
    document.getElementById('firstAdd').innerHTML=randomNumber();
    document.getElementById('secondAdd').innerHTML=randomNumber();
}

function randomNumber()
{
    var number = Math.floor(Math.random()*50) + 1; //Generates a random number between 1-50
    return number;
}

function nextQuestion()
{
    if(txtAnswer.value === "") //Check to see if they answered the question
    {
        alert("You didn't answer the question."); //Tell them they didn't
    }
    else
    {
        questionTop[questionMarker] = document.getElementById('firstAdd').innerHTML * 1; //Stores the top random number in the array
        questionBot[questionMarker] = document.getElementById('secondAdd').innerHTML * 1; //Stores the bottom random number in the array
        answers[questionMarker] = txtAnswer.value; //Stores the answer given by the user
        correct[questionMarker] = questionTop[questionMarker] + questionBot[questionMarker]; //Calculates and stores the correct answer
        if(answers[questionMarker] == correct[questionMarker]) //Checks to see if they got the answer right
        {
            alert("You got the question right!"); //Tells them so
            correctAnswers++; //Counts the correct answer for later
        }
        else
        {
            alert("Sorry that was not the correct answer." + '\n' + "You answered " + answers[questionMarker] + '\n' + "The correct answer was " + correct[questionMarker]); //Tells them the answer if they got it wrong and compares to their answer
        }
        document.getElementById('firstAdd').innerHTML=randomNumber(); //Generates new top random number
        document.getElementById('secondAdd').innerHTML=randomNumber(); //Generates new bottom random number
        txtAnswer.value = ""; //Clears the answer field
        txtCarry.value = ""; //Clears the carry field
        questionMarker++; //Increments the questionMarker so we know how many questions we've answered.
    }
    if(questionMarker == 10) //If we've answered 10 questions...
    {
        alert("You have completed the quiz!"); //The quiz is completed
        document.write("Your Answers:"); //Displays their answers
        document.write('\n' + questionTop[0] + " + " + questionBot[0] + " = " + answers[0] + "  Correct Answer is: " + correct[0]);
        document.write('\n' + questionTop[1] + " + " + questionBot[1] + " = " + answers[1] + "  Correct Answer is: " + correct[1]);
        document.write('\n' + questionTop[2] + " + " + questionBot[2] + " = " + answers[2] + "  Correct Answer is: " + correct[2]);
        document.write('\n' + questionTop[3] + " + " + questionBot[3] + " = " + answers[3] + "  Correct Answer is: " + correct[3]);
        document.write('\n' + questionTop[4] + " + " + questionBot[4] + " = " + answers[4] + "  Correct Answer is: " + correct[4]);
        document.write('\n' + questionTop[5] + " + " + questionBot[5] + " = " + answers[5] + "  Correct Answer is: " + correct[5]);
        document.write('\n' + questionTop[6] + " + " + questionBot[6] + " = " + answers[6] + "  Correct Answer is: " + correct[6]);
        document.write('\n' + questionTop[7] + " + " + questionBot[7] + " = " + answers[7] + "  Correct Answer is: " + correct[7]);
        document.write('\n' + questionTop[8] + " + " + questionBot[8] + " = " + answers[8] + "  Correct Answer is: " + correct[8]);
        document.write('\n' + questionTop[9] + " + " + questionBot[9] + " = " + answers[9] + "  Correct Answer is: " + correct[9]);
        document.write('\n' + "You got " + correctAnswers + " answers right out of 10."); //Shows how many answers they got right
        document.write('\n' + "You got " + correctAnswers*10 + "% of the questions right."); //Calculates their percent right
        document.write('\n' + '<button id="newQuiz" type="button" onclick="window.location.reload()">New Quiz</button>'); //Creates new button to reload the screen and start again
    }
}

</script>

Он расположенвеб здесь: http://www.innogeek.com/java/index.html Код в iFrame на http://www.innogeek.com/java/frame.html

Ответы [ 3 ]

2 голосов
/ 30 января 2012

Вы не объявили переменную txtAnswer перед ее использованием.

2 голосов
/ 30 января 2012

Изменить nextQuestion() на:

function nextQuestion()
{
    var txtAnswer = document.getElementById('txtAnswer'); //<-- ADD THIS
    var txtCarry = document.getElementById('txtCarry'); //<-- AND THIS

    if(txtAnswer.value === "") //Check to see if they answered the question
    {
        alert("You didn't answer the question."); //Tell them they didn't
    }
...
}

Ваша проблема заключалась в том, что вы не определяли переменную txtAnswer до того, как использовали ее.

Некоторые браузеры автоматически сопоставляют идентификаторы DOM с переменными Javascript (я полагаю, что IE делает то же самое), но вы не можете действительно рассчитывать на это.

0 голосов
/ 30 января 2012

Ваша проблема в том, что нет определенной переменной с именем txtAnswer. Я предполагаю, что Chrome отображает элементы DOM с идентификатором в переменные с тем же именем (это поведение, на которое нельзя полагаться). Я предлагаю вам добавить эту строку, чтобы начать вашу nextQuestion функцию:

var txtAnswer = document.getElementById("txtAnswer");
...