变量跟踪用户尝试次数不会更新

时间:2018-11-25 11:19:11

标签: javascript html performance variables

我正在做一个测验游戏,并且我已经有一段时间了这个问题,我只是弄不清楚我在做什么错。询问任何问题,如果您对我的解释感到困惑,我将监视该帖子

如何重现该问题-键入屏幕上显示的名称,直到看到“ Game over bro!”。 -- 问题: 当我在输入字段中输入名称并单击“答案”以检查输入字段值是否与从API检索到的名称匹配时,会有一个变量(var尝试= 5)跟踪用户尝试了该问题的次数,但是当答案正确时,此变量(尝试)会将其值减小1,只有在答案错误时才应这样做。

另外,让我知道您对JS代码的看法,这是不好的代码吗? 我问是因为newReq函数中的代码我写了两次,一次是在页面加载时加载并显示从API检索的数据,newReq函数中的代码是在单击“新字符”按钮时加载了新字符。一直在考虑DRY,但我不确定如何在不重写代码的情况下加载新字符

var attemptsPara = document.querySelector("#attempts"),
  attempts = 5,
  scorePara = document.querySelector("#score"),
  score = 0,
  feedBackDiv = document.querySelector("#feedBack"),
  newCharacterBtn = document.querySelector("#newCharacter"),
  answerBtn = document.querySelector("#answer"),
  input = document.querySelector("input");

scorePara.textContent = `Score is currently: ${score}`;
attemptsPara.textContent = `${attempts} attempts remaining`;

var feedBackText = document.createElement("p");

var characterPara = document.querySelector("#character");

//click new character button to load new character
// newCharacterBtn.addEventListener("click", () => {
//   answerBtn.disabled = false;
//   attempts = 5;
//   attemptsPara.textContent = `${attempts} attempts remaining`;
// });

//function that displays retrieved data to the DOM
function displayCharacters(info) {
  let englishName = info.attributes.name;
  characterPara.textContent = `This is the character's name: ${englishName}`;
  console.log(englishName, randomNumber);
}


//load new character
var randomNumber = Math.round(Math.random() * 100 + 2);
var request = new XMLHttpRequest();
request.open(
  "GET",
  "https://kitsu.io/api/edge/characters/" + randomNumber,
  true
);

request.send();

request.onload = function() {
  var data = JSON.parse(this.response);
  var info = data.data;
  displayCharacters(info);

  //checks if the input value matches name retrieved
  answerBtn.addEventListener("click", () => {
    let englishName = info.attributes.name;
    if (input.value === englishName) {
      feedBackText.textContent = `${input.value} is correct`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "green";
      feedBackDiv.style.display = "block";
      setTimeout(() => {
        feedBackDiv.style.display = "none";
      }, 3000);
      score = score + 5;
      scorePara.textContent = `Score is currently: ${score}`;
      attempts = 5;
      attemptsPara.textContent = `${attempts} attempts remaining`;
      input.value = "";
      newReq(); //call function to load and display new character
    } else {
      feedBackText.textContent = `${input.value} is wrong`;
      feedBackDiv.append(feedBackText);
      feedBackDiv.style.backgroundColor = "red";
      feedBackDiv.style.display = "block";
      input.focus();
      setTimeout(() => {
        feedBackDiv.style.display = "none";
      }, 2000);
      attempts = attempts - 1;
      attemptsPara.textContent = `${attempts} attempts remaining`;

      if (attempts <= 0) {
        answerBtn.disabled = true;
        attemptsPara.textContent = `Game over bro!`;
      }
    }
    console.log(attempts); //check how many attempts remaining every time answerBtn is clicked
  });
};

newCharacterBtn.addEventListener("click", newReq);

//function to make a new request and display it the information on the DOM,when New character button is clicked
function newReq() {
  rand = randomNumber = Math.round(Math.random() * 100 + 2);
  var request = new XMLHttpRequest();
  request.open(
    "GET",
    "https://kitsu.io/api/edge/characters/" + randomNumber,
    true
  );

  request.send();

  request.onload = function() {
    var data = JSON.parse(this.response);
    var info = data.data;
    displayCharacters(info);

    answerBtn.addEventListener("click", () => {
      let englishName = info.attributes.name;
      if (input.value === englishName) {
        feedBackText.textContent = `${input.value} is correct`;
        feedBackDiv.append(feedBackText);
        feedBackDiv.style.backgroundColor = "green";
        feedBackDiv.style.display = "block";
        //settimeout to hide feedBack div
        setTimeout(() => {
          feedBackDiv.style.display = "none";
        }, 3000);
        score = score + 5;
        scorePara.textContent = `Score is currently: ${score}`;
        attempts = 5;
        attemptsPara.textContent = `${attempts} attempts remaining`;
        input.value = "";
        newReq();
      } else if (input.value != englishName) {
        feedBackText.textContent = `${input.value} is wrong`;
        feedBackDiv.append(feedBackText);
        feedBackDiv.style.backgroundColor = "red";
        feedBackDiv.style.display = "block";
        input.focus();
        //settimeout to hide feedBack div
        setTimeout(() => {
          feedBackDiv.style.display = "none";
        }, 2000);
        attempts = attempts - 1;
        attemptsPara.textContent = `${attempts} attempts remaining`;

        if (attempts <= 0) {
          answerBtn.disabled = true;
          attemptsPara.textContent = `Game over bro!`;
        }
      }
    });
    console.log(attempts);
  };
}
body {
  margin: 0;
  padding: 0;
  background: black;
}

#imageHolder {
  height: 560px;
  width: 1100px;
  background: #098;
  margin: 10px auto;
}

#buttonHolder {
  /* background: #453; */
  width: 160px;
  margin: 0 auto;
}

p,
h3 {
  color: yellowgreen;
  text-align: center;
}

h3 {
  text-decoration: underline;
}

img {
  width: 100%;
  height: 100%;
}

button,
input {
  margin: 10px 10px;
  border: none;
  background: #098;
  display: block;
}

input {
  background: white;
}


/* for the question and awnswer game */

#feedBack {
  background: #098;
  height: 120px;
  width: 320px;
  margin: 10px auto;
  display: none;
}
<p id="score"></p>

<p id="character"></p>

<input type="text"> <button id="answer">Answer</button> <button id="newCharacter">New Character</button>

<p id="attempts"></p>

<div id="feedBack">

</div>

1 个答案:

答案 0 :(得分:0)

您的问题是每当答案返回时都调用answerBtn.addEventListener产生的,这会增加越来越多的听众。

click事件的开始处添加控制台日志,您会看到在第二个答案之后,单击事件发生了两次,然后在第三个答案上发生了三次,依此类推。 这意味着第一次单击结果是正确的,但随后的其他单击结果是不正确的,并且一定是导致错误的原因。

您应该只侦听一次事件,该事件使用的变量会发生变化,这应该足够了。抱歉,我目前无法为您修复代码。