布尔条件总是计算为false

Boolean condition always evaluating to false

本文关键字:false 计算 条件 布尔      更新时间:2023-09-26

基本上我有我的程序,这是一个测试,我在一个布尔值中得到了一个意外的结果。我所指的布尔条件是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 -->

演示

非常感谢您的协助。

您需要替换此:

var userChoice = convertOptionToNumber(attr);

使用此代码:

var userChoice = convertOptionToNumber(this.id);

你试图做的-为每个选项定义属性vrable是不可行的,因为它是在一般范围内定义的。如果你想保持属性的价值,你可以这样做:

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。这是调用函数的元素。

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

(对不起我的英语)

我对您的代码进行了一些更改以正确运行它(请参阅控制台)检查这个

    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;
 }

 }

问题是您在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);
}

我设法修复了这个错误。这与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)

    }
}