這是我的第一篇文章,所以請原諒我的任何輕率!我幾乎在我的智慧結局,因爲我已經在這個幾個小時了,我相信徹底完成了我的研究並嘗試了一些解決方案。我在編程方面也很新,但認爲自己是一個快速學習者!具有挑戰性的Javascript比較問題(總是返回false)|測試/研究之前
在下面的代碼中,我試圖比較「buttonClicked」變量,它將this.innerText值從已經在頁面上單擊的按鈕轉換爲「triviaAnswer」變量,該變量接收來自數組「 arrayOfTrivias [j] .answer「,它從triviaArray中的當前索引對象中提取其值。
即使我可以console.log這兩個值,他們都顯示爲相同的值,每當他們打我的if語句,所有按鈕將返回一個錯誤的匹配(即使按鈕匹配)「triviaAnswer 「或真正的匹配(甚至不匹配的按鈕)到」triviaAnswer「,具體取決於正在運行的比較屬性。
我曾嘗試沒有成功以下
〜單/兩瓦爾(雖然我可能錯過了一些東西!):toString()
,indexOf
,typeOf
〜運營商:===
,==
,.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>
感謝您的快速響應!你不知道我花了多少個小時,研究和檢查我的代碼是否有單個錯字......謝謝!這是一種犯罪,我不能投票... –
我認爲OP應更新原始變量,而不是有條件地評估修剪過的字符串。否則,他們不僅要記住每次都這樣做,還要在每個條件語句中執行trim()操作。似乎沒有必要。 –
@Luke Stoward你是對的。我編輯過。 – RogerC