2017-09-04 38 views
0

這是我的第一篇文章,所以請原諒我的任何輕率!我幾乎在我的智慧結局,因爲我已經在這個幾個小時了,我相信徹底完成了我的研究並嘗試了一些解決方案。我在編程方面也很新,但認爲自己是一個快速學習者!具有挑戰性的Javascript比較問題(總是返回false)|測試/研究之前

在下面的代碼中,我試圖比較「buttonClicked」變量,它將this.innerText值從已經在頁面上單擊的按鈕轉換爲「triviaAnswer」變量,該變量接收來自數組「 arrayOfTrivias [j] .answer「,它從triviaArray中的當前索引對象中提取其值。

即使我可以console.log這兩個值,他們都顯示爲相同的值,每當他們打我的if語句,所有按鈕將返回一個錯誤的匹配(即使按鈕匹配)「triviaAnswer 「或真正的匹配(甚至不匹配的按鈕)到」triviaAnswer「,具體取決於正在運行的比較屬性。

我曾嘗試沒有成功以下

〜單/兩瓦爾(雖然我可能錯過了一些東西!):toString()indexOftypeOf

〜運營商:=====.eq()

〜將兩個變量傳遞到空白字符串進行比較

〜將變量的位置切換到c比較

我的目標是從點擊按鈕中獲取字符串值,看它是否與'triviaAnswer'相匹配。

所有的代碼都是我的(除了明顯的CDN鏈接)。

任何和所有的幫助是肯定感激!如果您碰巧解決了這個問題,請解釋您是如何找到解決方案的,因爲我想從此體驗中學習! :-)

比較問題發生在「On-Click Events」部分。

這裏是我的代碼:

的JavaScript

$(document).ready(function() { 
    //This is the array we will use to store our trivia objects. 
    var triviaArray = []; 

    /** 
    * Set the start of the array. We will also use this to keep track of our 
    * place is the array. 
    * Set it to minus so we can go to the first objext (0) in the array when we 
    * begin. 
    */ 
    var j = -1; 

    //Countdown timer variables 
    var countdownNumber = 60; 
    var intervalId; 

    //button trackers 
    var buttonClicked; 

    //comparison variables 
    var triviaAnswer; 

    //score variables 
    var correctAnswers = 0; 
    var incorrectAnswers = 0; 
    var noAnswers = 0; 

    var triviaObj1 = { 
    question: "What is the highest grossing anime film worldwide?", 
    options: ["Spirited Away", "Howl's Moving Castle", "Your Name", "Pokemon The Movie"], 
    answer: "Your Name" 
    } 
    var triviaObj2 = { 
    question: "What is an Otaku?", 
    options: ["A type of sushi", "A type of anime fan", "A type of bullet train", "A type of bonsai"], 
    answer: "A type of anime fan" 
    } 
    var triviaObj3 = { 
    question: "What is historically the most popular professional sport in Japan?", 
    options: ["Baseball", "Basketball", "Sumo Wrestling", "Marital Arts"], 
    answer: "Baseball" 
    } 
    triviaArray = [triviaObj1, triviaObj2, triviaObj3]; 

    $("#startButton").on("click", function() { 
    // pass the array of triviaObjects to the triviaGenerator 
    triviaGenerator(triviaArray); 

    //Start the countdown/timer 
    countdownTimer(); 

    //Hide start button afterward pressed, we won't need it anymore 
    $("#startButton").hide(); 
    }); 

    // handles the user button clicks 
    $("body").on("click", ".optionButton", function() { 
    buttonClicked = this.innerText; 
    //if user clicks on an option button, run the following 
    if ($(this).parent().attr('id') === "optionsContainer") { 
     console.log("buttonClicked:", buttonClicked); 
     console.log("triviaAnswer:", triviaAnswer); 
     //Run the comparison, check the buttons text and the "answer" from the 
     object. StackOverflow "Problem If Statement Here" 
     if (buttonClicked == triviaAnswer) { 
     alert("CORRECT"); 
     } else { 
     alert("WRONG"); 
     } 
    } 
    }); 

    function countdownTimer() { // this will be our countdown timer. 
    intervalId = setInterval(decrement, 1000); 
    } 

    function decrement() { // The decrement function. 
    countdownNumber--; 
    $("#countdown").html("<h2>" + countdownNumber + "</h2>"); 
    if (countdownNumber === 0) { 
     timesUp(); //run the gameOver function. 
    } 
    } 

    function timesUp() { 
    clearInterval(intervalId); 
    countdownNumber = 60; //reset and restart the countdown. 
    countdownTimer(); 
    triviaGenerator(triviaArray); //move to the next trivia object. 
    } 

    function triviaGenerator (arr) { // We will use this function to generate our array. 
    var arrayOfTrivias = arr; 
    j = j + 1; //Go up one in the array (go to the next object in the array) 
    j = j % arrayOfTrivias.length; // end of the array ? -> go back to the beginning 
    triviaAnswer = arrayOfTrivias[j].answer; //assign the trivia's answer to a global variable so we can do a comparison against the users answer 

    //Print the trivia's question to the page 
    //Make sure the div is clear for the insertion of the trivia's question 
    $("#questionContainer").text(""); 

    //Insert the question for the trivia we are on 
    var triviaQuestion = arrayOfTrivias[j].question; 
    $("#questionContainer").append("<h2>" + triviaQuestion + "</h2>"); 

    var optionsArray = arrayOfTrivias[j].options; 

    // Loop through the options array for this trivia and print//append them as buttons to the screen. 
    $("#optionsContainer").text(""); 
    for (var i = 0; i < optionsArray.length; i++) { 
     $("#optionsContainer").append("<button class='optionButton btn btn-default'>" + "<h2>" + optionsArray[i] + "</h2> </button>"); 
    } 
    } 
}); 

HTML

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Trivia Game</title> 
    <link rel="stylesheet" type="text/css" href="style.css"> 
    </head> 

    <body> 
    <nav class="navbar navbar-inverse header"> 
     <div class="container-fluid"> 
     Header/Navbar here 
     </div> 
    </nav> 
    <div class="container-fluid text-center"> 
     <div class="row content"> 
     <div class="col-sm-2 sidenav"></div> 
     <div class="col-sm-8 left-center"> 
      <p id="welcomeBanner"> Welcome to the Trivia Page</p> 
      <div id="dynamicDiv"> 
      <button id="startButton" class="btn btn-danger center"> 
       Start 
      </button> 
      <div id="countdown"></div> 
      <div id="questionContainer"></div> 
      <div id="optionsContainer"></div> 
      </div> 
     </div> 

     <div class="col-sm-2 sidenav"></div> 
     </div> 
    </div> 
    <footer class="container-fluid text-center footer"> 
     <p> Footer Text </p> 
    </footer> 
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> 
    <script type="text/javascript" src="script.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXT sjBbfaDjzALeQsN6M" crossorigin="anonymous"> 
    </body> 
</html> 

回答

2

似乎是在buttonClicked變量的額外空間。

您可以使用裝飾和您的病情作品:

buttonClicked = this.innerText.trim(); 
if (buttonClicked == triviaAnswer) { 

} 

@Luke Stoward評論後編輯

+0

感謝您的快速響應!你不知道我花了多少個小時,研究和檢查我的代碼是否有單個錯字......謝謝!這是一種犯罪,我不能投票... –

+1

我認爲OP應更新原始變量,而不是有條件地評估修剪過的字符串。否則,他們不僅要記住每次都這樣做,還要在每個條件語句中執行trim()操作。似乎沒有必要。 –

+0

@Luke Stoward你是對的。我編輯過。 – RogerC

2

嘗試這樣比較兩個值:

if (buttonClicked.trim() == triviaAnswer.trim()) {..... 

有時是一個空白的地方在由Javascripts trim()函數切出的末尾。

+0

非常感謝您的回覆!我不知道!這是一種生活品味!再次,這是犯罪我不能投票! –

1

看起來,當您撥打buttonClicked = this.innerText;時,檢索到的值確實在結尾處有一些空白字符。您可以通過登錄該變量的長度與console.log(buttonClicked.length);

證實了這一點要解決這個問題,你必須修剪空白字符,像這樣

buttonClicked = buttonClicked.trim();

我創造了這個小提琴(與您的代碼),演示修復和工作程序:https://jsfiddle.net/fu3szacb/2/

附註:我會避免在JavaScript中聲明全局變量,這是不好的做法,並可能導致混亂和痛苦的世界。學習語言時最好避免這種情況。

提供有關全局變量上下文的有用鏈接,以及爲什麼應該避免它們。 (有許多來源)https://www.w3schools.com/js/js_scope.asp

0

正如大家所說,這可能是對的空白和不修剪,你可以嘗試只通過

buttonClicked = buttonClicked.trim(); 

但我要補充的是即將在Javascript中比較字符串時,你有要小心比較,通常trim()以及在兩個變量中使用toLowerCase()或toUpperCase()進行比較。

此外,對於這種情況,我絕不會僅僅依靠比較字符串,因爲您要重寫正確的字符串,並且可以使許多錯字錯誤。如果我是你,我每次都會用編號答案來使用一系列答案,所以你只需要檢索數字並進行比較,這樣更安全,更容易。

您可以在每個答案變量中保存正確答案的位置數量/索引,如果您擔心的是從HTML中捕獲數字,我看到您使用的是jQuery。你可以只隱藏在每一個選項標籤中的每個選項的數量作爲屬性

numberAnswer="2" 

clickedNumberAnswer = $(this).attr('numberAnswer') 

得到公正行

if ($(this).parent().attr('id') === "optionsContainer") { 

所以比較就變得

下方
if(clickedNumberAnswer == triviaAnswer) 

現在如果遇到空白問題並且不可能區分大小寫問題,那將非常奇怪。現在triviaAnswer應該包含一個數字,如果我的記憶足夠好,那麼在比較「2」== 2時,Javascript會自動轉換,所以它會更好。