gpt4 book ai didi

javascript - 具有挑战性的 Javascript 比较问题(总是返回 false) |发布前进行测试/研究

转载 作者:行者123 更新时间:2023-11-28 13:06:41 25 4
gpt4 key购买 nike

这是我第一次发帖,如有不当之处还请多多包涵!我几乎束手无策,因为我已经这样做了几个小时,我相信已经彻底完成了我的研究并尝试了很多解决方案。我在编程方面也是新手,但我认为自己学得很快!

在下面的代码中,我试图将“buttonClicked”变量与“triviaAnswer”变量进行比较,该变量从页面上单击的按钮获取 this.innerText 值,该变量从数组“arrayOfTrivias”接收其值[j].answer”,它从 triviaArray 中的当前索引对象中提取其值。

即使我可以 console.log 这两个值并且它们都显示为相同的值,但每当它们命中我的 if 语句时,所有按钮都会向“triviaAnswer”返回错误匹配(甚至是匹配的按钮)或与“triviaAnswer”的真正匹配(甚至不匹配的按钮),具体取决于正在运行的比较属性。

我尝试了以下方法但没有成功(尽管我可能错过了一些东西!)

~单/两个变量:toString()indexOftypeOf

~运算符:=====.eq()

~将两个变量传递到空白字符串中进行比较

~在比较中切换变量的位置

我的目标是从单击的按钮获取字符串值,并查看它是否与“triviaAnswer”匹配。

所有代码都是我的(除了明显的 CDN 链接)。

非常感谢任何和所有的帮助!如果您碰巧解决了这个问题,请解释一下您是如何找到解决方案的,因为我想从这次经验中学习! :-)

比较问题发生在“点击事件”部分。

这是我的代码:

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>

最佳答案

buttonClicked 变量中似乎有一个额外的空格。

您可以使用 trim 并且您的条件有效:

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

}

在 @Luke Stoward 评论后编辑

关于javascript - 具有挑战性的 Javascript 比较问题(总是返回 false) |发布前进行测试/研究,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46033126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com