Удалить текст после того, как ответ был сделан с помощью jQuery / JavaScript - PullRequest
0 голосов
/ 02 июля 2018

Думаю, у меня возникла проблема с логикой. Что должно произойти, пользователь введет ответ на заданный вопрос. Как только вопрос будет отправлен, текущий текст (первый вопрос) исчезнет, ​​и вместо первого вопроса появится следующий вопрос в массиве.

В настоящее время вопросы продолжают накапливаться друг без друга, не удаляя предыдущий вопрос. Каждый раз, когда я пытаюсь добавить больше кода для удаления элемента, он выдает ошибку.

Пожалуйста, помогите! Я медленно добавляю к этой функциональности кодов, но теперь я застрял в этой функции добавления / удаления текста.

$(function() {
  $("#submit").on("click", askQuestion)

  var questions = [{
      question: "Is the price higher or lower than $40.00?",
      answer: "higher"
    },
    {
      question: "Is the price higher or lower than $100.00?",
      answer: "higher"
    },
    {
      question: "Is the price higher or lower than $50.00?",
      answer: "lower"
    }
  ];

  function askQuestion() {
    if (answer && document.querySelector("#user-answer").value == answer) {
      document.querySelector("#correct").style.display = "block";
      document.querySelector("#sorry").style.display = "none";
      answer = randomQuestion()
    } else {
      document.querySelector("#correct").style.display = "none";
      document.querySelector("#sorry").style.display = "block";

    }
  }

  function randomQuestion() {
    var question = questions[Math.floor(Math.random() * questions.length)];

    document.querySelector("#user-answer").value = "";

    var element = document.createElement("div");
    element.innerHTML = question.question;

    $("#question").append(element.firstChild);

    return question.answer;
  }

  var answer = randomQuestion();
});
<html>
<head>
  <meta charset="UTF-8">
  <title>Game time</title>
</head>
<body>
  <h1>Question and Answer</h1>
  <div>
    <h2 id="question"></h2>
  </div>
  <label for="text">Answer:</label>
  <input id="user-answer" type="text" value="">
  <button id="submit" type="submit">Submit</button>
  <p id="sorry" style="display: none">Sorry...</p>
  <p id="correct" style="display: none">You got it!</p>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  <script src="main.js"></script>
</body>
</html>

Ответы [ 2 ]

0 голосов
/ 02 июля 2018

Вы используете метод добавления. Если вы хотите полностью переопределить текст, вы можете использовать метод .text (jQuery) или .innerText (Vanilla js)

0 голосов
/ 02 июля 2018

Вы просто используете append, когда вам нужно изменить вопрос, а не , добавляя к нему .

Вы можете использовать: $("#question").html(element.firstChild);

вместо $("#question").append(element.firstChild);

$(function() {

  $("#submit").on("click", askQuestion)

  var questions = [{
      question: "Is the price higher or lower than $40.00?",
      answer: "higher"
    },
    {
      question: "Is the price higher or lower than $100.00?",
      answer: "higher"
    },
    {
      question: "Is the price higher or lower than $50.00?",
      answer: "lower"
    }
  ];

  function askQuestion() {
    if (answer && document.querySelector("#user-answer").value == answer) {
      document.querySelector("#correct").style.display = "block";
      document.querySelector("#sorry").style.display = "none";
      answer = randomQuestion()
    } else {
      document.querySelector("#correct").style.display = "none";
      document.querySelector("#sorry").style.display = "block";

    }
  }


  function randomQuestion() {
    var question = questions[Math.floor(Math.random() * questions.length)];

    document.querySelector("#user-answer").value = "";

    var element = document.createElement("div");
    element.innerHTML = question.question;

    $("#question").html(element.firstChild);

    return question.answer;

  }

  var answer = randomQuestion();

});
<html>

<head>
  <meta charset="UTF-8">
  <title>Game time</title>
</head>

<body>
  <h1>Question and Answer</h1>
  <div>
    <h2 id="question"></h2>
  </div>
  <label for="text">Answer:</label>
  <input id="user-answer" type="text" value="">
  <button id="submit" type="submit">Submit</button>

  <p id="sorry" style="display: none">Sorry...</p>
  <p id="correct" style="display: none">You got it!</p>

  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  <script src="main.js"></script>
</body>

</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...