【问题标题】:Boolean condition always evaluating to false布尔条件总是评估为假
【发布时间】:2015-03-25 20:13:24
【问题描述】:

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

以下是程序代码:

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

非常感谢您的帮助。

【问题讨论】:

  • 快速说明,因为您使用的是 html5 标记:如果 llink 元素是 rel=stylesheet,则不需要“类型”除非它不是 CSS
  • 你试过调试吗? console.log() 相关变量,看看它们是什么。对代码中的所有相关值执行此操作,直到找到实际与您的期望不同的地方。
  • 这个parseInt(correct); 没有给任何东西赋值。真的什么都没做。
  • 一些快速调试表明userChoice 始终为 3。设置一些断点并向后工作,直到找到逻辑错误。

标签: javascript function boolean


【解决方案1】:

你需要替换这个:

var userChoice = convertOptionToNumber(attr);

使用此代码:

var userChoice = convertOptionToNumber(this.id);

您尝试做的 - 为每个选项 vriable 定义 attr 是行不通的,因为它是在一般范围内定义的。如果你想保持 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/

(对不起我的英语)

【讨论】:

  • 您能否解释一下为什么它没有按 OP 的预期工作?这将对 OP 有很大帮助
  • 没错,每次添加optionClickHandler时attr都会递增。所以 attr 的值一直在变化。当使用 this.id 时,您使用的是被点击的元素 id。
  • 您好 Elad 非常感谢您抽出宝贵时间回答我的问题并为我提供帮助。当您说可以删除选项单击处理程序时,我不确定您的意思-我需要它来处理对问题选项的单击。
  • 另外我可以看到您将 attr 变量设为本地,我将在哪里添加 this.id 作为参数?
  • 您可以通过在每个选项中添加onclick="checkCorrectAnswer()"来替换optionClickHandler
【解决方案2】:

我对您的代码进行了一些更改以正确运行它(请参阅控制台)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;
 }


 }

【讨论】:

  • 据我所知,返回后没有必要使用 break 语句,因为它们永远不会到达。
【解决方案3】:

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

}

【讨论】:

    【解决方案4】:

    我设法修复了错误。这与 attr 变量中的值无关,而是导致问题的 for 循环。我删除了 for 循环并为每个 ID 创建了 4 个变量。 for 循环总是将最后一个 options 属性分配给 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)
    
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2019-09-01
      • 2017-01-22
      相关资源
      最近更新 更多