이것은 내 첫 번째 게시물이기 때문에 어떠한 분규라도 용서해주십시오! 나는 거의 몇 시간 동안이 일을 해왔으므로 나의 연구를 철저히 수행하고 많은 해결책을 시도했다. 나는 또한 프로그래밍에서 새로운 것 같지만 자신을 빠른 학습자로 생각합니다!도전적인 자바 스크립트 비교 문제 (항상 false 반환) | 게시하기 전에 테스트/조사했습니다.
아래 코드에서 this.innerText 값을 페이지에서 클릭 한 "triviaAnswer"변수에서 값을 가져 오는 변수와 비교하는 "buttonClicked"변수를 비교하려고합니다 " arrayOfTrivias [j] .answer "는 triviaArray의 현재 색인 객체에서 해당 값을 가져옵니다.
비록 내가 console.log에서 값과 두 값이 모두 동일한 값으로 표시 될 수 있지만, if 문을 때릴 때마다 모든 버튼이 "triviaAnswer"와 일치하는 false match (일치하는 버튼조차도)를 반환합니다. "또는 비교 속성에 따라"triviaAnswer "에 true match (일치하지 않는 버튼조차도)를 실행합니다.
는 나는 아무 성공 다음 시도
~ 하나/둘 다 바르 (내가 뭔가를 놓친 수도 있지만!) : toString()
, indexOf
, typeOf
~ 운영자 : ===
, ==
, .eq()
~ 비교를 위해 두 변수를 빈 문자열에 전달
~ c에서 변수의 위치를 전환하는 중 omparison
내 목표는 클릭 한 버튼에서 문자열 값을 가져 와서 'triviaAnswer'와 일치하는지 확인하는 것입니다.
모든 코드는 내 것입니다 (명백한 CDN 링크 제외).
모든 도움말이 가장 좋습니다. 이 문제를 해결하려는 경우,이 경험을 통해 배우고 자하는 솔루션을 어떻게 찾았는지 설명하십시오! :-)
"On-Click Events"섹션에서 비교 문제가 발생합니다.
자바 스크립트
$(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