布尔条件总是评估为false

时间:2015-03-25 20:13:24

标签: javascript function boolean

基本上我有我的程序,这是一个测验,我在我的一个布尔值中得到一个意外的结果。我所指的布尔条件是checkCorrectAnswer函数中的一个。在这里,我正在测试是否已经点击了正确的答案 - 如果有,那么它应该评估为true,否则为false并在else语句之后执行所有操作。但是if条件总是评估为false,即使我点击正确答案,我也会收到“不正确”。

以下是程序代码:

window.onload = function() {
    var attr;
    var currentQuestion = 0;

    var allQuestions = [{
            question: 'Which turkish club did former Leeds player Harry Kewell join in 2008, which caused an uproar amongst Leeds supporters?',
            choices: ['Galatasaray', 'Besiktas', 'Fenerbahce', 'Sivaspor'],
            correctAnswer: 0
        },

        {
            question: 'Who is the former Liverpool star who beat Ruud Van Nistelrooy\'s record of most prolific foreign goalscorer in their debut in the Premier League?',
            choices: ['Micheal Owen', 'Xabi Alsonso', 'Luis Suarez', 'fernando Torres'],
            correctAnswer: 3
        },

        {
            question: 'Who scored Liverpool\s winner in \'that\' first 4-3 game against Kevin Keegan\'s Newcastle United in April 1996?',
            choices: ['Stan Collymore', 'Phil Baab', 'Steven Gerrard', 'Jamie Carragher'],
            correctAnswer: 0
        },

        {
            question: 'Which former Aston Villa and Ireland midfielder went on to become a regular TV pundit with ITV?',
            choices: ['Dwight Yorke', 'Stan Collymore', 'Andy Townsend', 'Steve Staunton'],
            correctAnswer: 2
        },

        {
            question: 'How many European Cups had Liverpool won up to and including 2007-8?',
            choices: ['8', '4', '5', '3'],
            correctAnswer: 2
        }
    ];



    //grab each of the option divs and assign the 4 options from array

    function loadQuestions(questionNumber) {
        var sequence = 1;
        var questionQuiz = document.getElementById('quiz-question');

        questionQuiz.innerHTML = allQuestions[questionNumber].question;


        for (var i = 0; i < 4; i++) {

            var option = document.getElementById('option' + sequence);
            sequence++;
            option.innerHTML = allQuestions[questionNumber].choices[i];

        }

    }




    loadQuestions(currentQuestion);


    //add evet listeners to each of the options 

    function optionClickHandler() {
        var sequence = 1;

        for (var i = 0; i < 4; i++) {

            var option = document.getElementById('choice' + sequence);

            attr = option.getAttribute("id");

            var show = convertOptionToNumber(attr);
            console.log(show);

            option.addEventListener("click", checkCorrectAnswer);
            sequence++;
        }


    }

    optionClickHandler();


    function convertOptionToNumber(option) {

        if (option === 'choice1') {

            option = 0;
        } else if (option === 'choice2') {

            option = 1;
        } else if (option === 'choice3') {

            option = 2;
        } else if (option === 'choice4') {

            option = 3;
        }

        return parseInt(option);

    }




    function checkCorrectAnswer() {

        var userChoice = convertOptionToNumber(attr);

        var correct = allQuestions[currentQuestion].correctAnswer;
        parseInt(correct);

        if (userChoice === correct) {

            alert('Correct!');

        } else {

            alert('Incorrect!');
        }

        console.log('The correct answer for question one ' + correct);

    }
}

这是index.html文件:

<!DOCTYPE html>

<head>
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
 </head>

 <div id="wrapper">  

 <h1>Football Quiz</h1>
<div id="question-number">
<p>You are on Question <span id="count"></span></p> 
</div> <!-- end of question counter div -->

 <div id="timer">
<p></p> 
</div> <!-- end of timer div -->
 <p id="quiz-question"></p>
 <div id="question-body">
<a id="choice1" href="#"><div  class="options">
    <p id="option1"></p>
</div></a>
<a id="choice2" href="#"><div  class="options">
    <p id="option2"></p>

 </div></a>
<a id="choice3" href="#"><div  class="options">
    <p id="option3"></p>
</div></a>
<a id="choice4" href="#"><div  class="options">
    <p id="option4"></p>
</div></a> 


 </div> <!-- end of question body div -->

Demo

非常感谢您的协助。

4 个答案:

答案 0 :(得分:1)

您需要替换它:

var userChoice = convertOptionToNumber(attr);

使用此代码:

var userChoice = convertOptionToNumber(this.id);

您尝试做什么 - 为每个选项定义attr vriable不起作用,因为它在一般范围内定义。如果你想保持attr的值,你可以这样做:

function optionClickHandler() {
        var sequence = 1;

        for (var i = 0; i < 4; i++) {

            var option = document.getElementById('choice' + sequence);

            var attr = option.getAttribute("id");

            var show = convertOptionToNumber(attr);
            console.log(show);
            var currCallback = createCheckCorrectCallback(attr);
            option.addEventListener("click", currCallback);
            sequence++;
        }


    }

    function createCheckCorrectCallback(attr) {
        return function() { // Now this function 'hold' the attr value
            checkCorrectAnswer(attr);
        };
    }

function checkCorrectAnswer(attr) { // Change the function call
    var userChoice = convertOptionToNumber(attr);
.....

但这是不必要的 - 您可以将attr参数替换为this.id。这是调用函数的元素。

jsFidlle与this.id解决方案 - http://jsfiddle.net/wwwercnL/1/ jsFidlle与闭包解决方案 - http://jsfiddle.net/wwwercnL/2/

(对不起我的英语)

答案 1 :(得分:0)

我对您的代码进行了一些更改,以便正确运行它(请参阅控制台)check this

    function convertOptionToNumber(option){
     switch(option){
           case 'choice1':
          return 0; 
          break;
        case 'choice2':

    return 1; 
             break;
        case 'choice3':

   return 2;
             break;
        case 'choice4':

    return 3; 
             break;
 }


 }

答案 2 :(得分:0)

问题是你在convertOptionToNumber()中调用convertOptionToNumber()时传递的参数,我稍微更改了你的代码,它运行正常:

function checkCorrectAnswer(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    var userChoice = convertOptionToNumber(targ.parentNode.parentNode.id);

    var correct = allQuestions[currentQuestion].correctAnswer;
    parseInt(correct);

    if (userChoice === correct) {

        alert('Correct!');

    } else {

        alert('Incorrect!');
    }

    console.log('The correct answer for question one ' + correct);

}

答案 3 :(得分:0)

我设法修复错误。它不是与attr变量中的值有关,而是导致问题的for循环。我删除了for循环并为每个ID创建了4个变量。 for循环始终将最后一个选项属性赋值给attr变量,这意味着在每种情况下attr变量都包含转换中的数字3。这是一个更新的功能:

function optionClickHandler(){

var option1 = document.getElementById('choice1');

var option2 = document.getElementById('choice2');

var option3 = document.getElementById('choice3');

var option4 = document.getElementById('choice4');


    option1.onclick = function(){

        checkCorrectAnswer(option1)


    }
    option2.onclick = function(){

            checkCorrectAnswer(option2)


    }
    option3.onclick = function(){

            checkCorrectAnswer(option3)


    }

    option4.onclick = function(){

            checkCorrectAnswer(option4)


    }

}