Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
挑战Javascript比较问题(总是返回false)|发布前测试/研究_Javascript_Jquery_Comparison - Fatal编程技术网

挑战Javascript比较问题(总是返回false)|发布前测试/研究

挑战Javascript比较问题(总是返回false)|发布前测试/研究,javascript,jquery,comparison,Javascript,Jquery,Comparison,这是我的第一篇帖子,所以请原谅我的任何轻率行为!我几乎束手无策,因为我已经在这几个小时了,我相信我已经彻底完成了我的研究,并尝试了很多解决方案。我能快速学习的人也有点新,但是我觉得自己很有学问。p> 在下面的代码中,我试图将“buttonClicked”变量与“triviaAnswer”变量进行比较,该变量从页面上单击的按钮中获取this.innerText值,该变量从数组“ArrayOftrivas[j].answer”接收其值,该数组从triviaArray中的当前索引对象提取其值 尽管我可

这是我的第一篇帖子,所以请原谅我的任何轻率行为!我几乎束手无策,因为我已经在这几个小时了,我相信我已经彻底完成了我的研究,并尝试了很多解决方案。我能快速学习的人也有点新,但是我觉得自己很有学问。p> 在下面的代码中,我试图将“buttonClicked”变量与“triviaAnswer”变量进行比较,该变量从页面上单击的按钮中获取this.innerText值,该变量从数组“ArrayOftrivas[j].answer”接收其值,该数组从triviaArray中的当前索引对象提取其值

尽管我可以console.log这两个值,并且它们都显示为相同的值,但每当它们点击我的if语句时,所有按钮都将返回与“triviaAnswer”的假匹配(甚至是匹配的按钮),或者与“triviaAnswer”的真匹配(甚至是不匹配的按钮),具体取决于运行的比较属性

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

~单个/两个变量:
toString()
indexOf
typeOf

~operators:
==
==
.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>");
    }
  }
});
$(文档).ready(函数(){
//这是我们用来存储琐事对象的数组。
var triviaArray=[];
/**
*设置数组的开始。我们还将使用它跟踪
*位置是数组。
*将其设置为负,这样我们可以在调用时转到数组中的第一个objext(0)
*开始。
*/
var j=-1;
//倒计时计时器变量
var countdownNumber=60;
var有效期;
//按钮跟踪器
点击var按钮;
//比较变量
var Trivia回答;
//分数变量
var=0;
var不正确答案=0;
var noAnswers=0;
变量triviaObj1={
问:“全球票房最高的动漫电影是什么?”,
选项:[《幽灵之旅》、《嚎叫的移动城堡》、《你的名字》、《口袋妖怪电影》],
回答:“你的名字”
}
变量triviaObj2={
问题:“什么是御宅族?”,
选项:[“一种寿司”、“一种动漫迷”、“一种子弹头列车”、“一种盆景”],
答:“一种动漫迷”
}  
变量triviaObj3={
问题:“日本历史上最受欢迎的职业运动是什么?”,
选项:[“棒球”、“篮球”、“相扑摔跤”、“婚姻艺术”],
回答:“棒球”
}
triviaArray=[triviaObj1,triviaObj2,triviaObj3];
$(“#开始按钮”)。在(“单击”,函数(){
//将Trivia对象数组传递给Trivia生成器
Trivia发生器(Trivia阵列);
//启动倒计时/定时器
倒计时();
//按下“隐藏开始”按钮后,我们将不再需要它
$(“#开始按钮”).hide();
});
//处理用户按钮的单击
$(“正文”)。在(“单击”,“选项按钮”,函数(){
buttonClicked=this.innerText;
//如果用户单击选项按钮,请运行以下命令
if($(this.parent().attr('id')=“optionsContainer”){
日志(“buttonClicked:”,buttonClicked);
日志(“triviaAnswer:,triviaAnswer”);
//运行比较,检查按钮文本和
object.StackOverflow“此处的If语句有问题”
如果(按钮点击==琐碎回答){
警惕(“正确”);
}否则{
警惕(“错误”);
}
}
});
函数countdownTimer(){//这将是我们的倒计时。
intervalId=设置间隔(减量,1000);
}
函数减量(){//减量函数。
倒计时数字--;
$(“#倒计时”).html(“+countdownNumber+”);
如果(倒计时编号===0){
timesUp();//运行gameOver函数。
}
}
函数timesUp(){
clearInterval(intervalId);
countdownNumber=60;//重置并重新开始倒计时。
倒计时();
trivia生成器(trivia数组);//移动到下一个trivia对象。
}
函数triviaGenerator(arr){//我们将使用此函数生成数组。
var arrayOfTrivias=arr;
j=j+1;//在数组中向上移动一个对象(转到数组中的下一个对象)
j=j%arrayOfTrivias.length;//数组的结尾?->返回到开头
triviaAnswer=arrayOfTrivias[j].answer;//将琐事的答案分配给一个全局变量,以便我们可以与用户的答案进行比较
//将琐事的问题打印到页面上
//确保div清楚地插入了琐事的问题
$(“#问题容器”).text(“”);
//为我们正在讨论的琐事插入问题
var triviaQuestion=arrayOfTrivias[j].问题;
$(“#questionContainer”).append(“+triviaQuestion+”);
var optionArray=arrayOfTrivias[j]。选项;
//循环浏览此琐事的选项数组并打印//将它们作为按钮附加到屏幕上。
$(“#选项容器”).text(“”);
对于(变量i=0;i
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 = this.innerText.trim();
if (buttonClicked == triviaAnswer) {

}
if (buttonClicked.trim() == triviaAnswer.trim()) {.....
buttonClicked = buttonClicked.trim();
numberAnswer="2" 
clickedNumberAnswer = $(this).attr('numberAnswer')
if ($(this).parent().attr('id') === "optionsContainer") {
if(clickedNumberAnswer == triviaAnswer)