Мой вывод javascript мигает на секунду, а затем исчезает - PullRequest
0 голосов
/ 28 апреля 2019

Мой Javascript выдает правильный вывод при первом взгляде, который я получаю, но по какой-то причине выход мигает на короткую секунду, а затем исчезает

Я не использую никаких фреймворков, и я работаю над базовым Javascript.

Я попытался проверить консоль на наличие выходных данных, но даже там она просто мигает.Я также попробовал это на firefox и edge, и та же проблема возникает

function MathRandom2() {
  let questionList = [];
  questionList.length = 10;
  let result = [];
  let operator = ['+', '-', '*', '/'];
  var numberRand = 0;

  // question variable will create the question based off the level choice. numberRand will be the limit.
  let question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
  let total = 0;
  var username = document.getElementById("username").value;


  //Line 12 to line 37 will check the radio button selection.
  if (document.getElementById("beginner").checked) {
    let result = confirm("Hey " + username + "! You have selected the beginner difficulty. Are you sure you wish to proceed?");
    if (result == true) {
      numberRand = 10;
    } else {
      return 0;
    }
  } else if (document.getElementById("intermediate").checked) {
    let result = confirm("Hey " + username + "! You have selected the intermediate difficulty. Are you sure you wish to proceed?");
    if (result == true) {
      numberRand = 20;

    } else {
      return 0;
    }
  } else if (document.getElementById("advanced").checked) {
    let result = confirm("Hey " + username + "! You have selected the advanced difficulty. Are you sure you wish to proceed?");
    if (result == true) {
      numberRand = 100;
    } else {
      return 0;
    }
  }


  for (let i = 0; i < questionList.length; i++) {
    let answer = parseInt(prompt("What is the answer to " + question));
    let correct = "<span style='background-color: #12CA00'>Your Answer to question </span> " + "<span  style='background-color: #12CA00'>" + i + "</span>" + "<span  style='background-color: #12CA00'> is correct</span>"
    let wrong = "<span style='background-color: #ca0002'>Your Answer to question </span> " + "<span  style='background-color: #ca0002'>" + i + "</span>" + "<span  style='background-color: #ca0002'> is wrong</span>"
    if (answer === eval(question)) {
      result.push(correct);
      question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
      total += 2;
    } else {
      result.push(wrong);
      question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);

    }
  }

  let display = result.join("</br>") + "</br>" + "You have got " + total + " marks";
  document.getElementById("result").innerHTML = display;
  console.log(display);
}
<div id="infoCol_main" class="infoCol_main">
  <script src="../Javascript/tute09.js"></script>
  <form>
    <h1>Welcome</h1>
    <fieldset>
      <label>Please enter your name here: <br><input type="text" id="username"  name="username" required></label><br>
      <label>Please choose your difficulty level: <br>
                    <input type="radio" name="difficulty" id="beginner" value="Beginner"  required>Beginner<br>
                    <input type="radio" name="difficulty" id="intermediate" value="Intermediate" required>Intermediate<br>
                    <input type="radio" name="difficulty" id="advanced" value="Advanced" required>Advanced<br>
                </label>
      <div class="buttonHold">
        <input type="submit" onclick="MathRandom2()" value="Begin">
      </div>
    </fieldset>
  </form>
</div>
<div>
  <p id="result"></p>
</div>

Мне нужно показать список ответов с измененным фоном на красный или зеленый в зависимости от того, был ли ответ неправильным или правильным соответственно.Вывод правильный, и я вижу его, но он там только на долю секунды, прежде чем он исчезнет enter code here

Ответы [ 2 ]

0 голосов
/ 28 апреля 2019

Использовать protectDefault ()

Метод интерфейса Event *1007* protectDefault () сообщает агенту пользователя, что, если событие не обрабатывается явно, его действие по умолчанию не должно выполняться, как обычно.

function MathRandom2() {

 const form = document.getElementById('form');

 form.addEventListener("submit", function(event){
   event.preventDefault(); // prevents form from submitting
 })

function MathRandom2() {

 const form = document.getElementById('form');

 form.addEventListener("submit", function(event){
   event.preventDefault();
 })

  let questionList = [];
  questionList.length = 10;
  let result = [];
  let operator = ['+', '-', '*', '/'];
  var numberRand = 0;

  // question variable will create the question based off the level choice. numberRand will be the limit.
  let question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
  let total = 0;
  var username = document.getElementById("username").value;


  //Line 12 to line 37 will check the radio button selection.
  if (document.getElementById("beginner").checked) {
    let result = confirm("Hey " + username + "! You have selected the beginner difficulty. Are you sure you wish to proceed?");
    if (result == true) {
      numberRand = 10;
    } else {
      return 0;
    }
  } else if (document.getElementById("intermediate").checked) {
    let result = confirm("Hey " + username + "! You have selected the intermediate difficulty. Are you sure you wish to proceed?");
    if (result == true) {
      numberRand = 20;

    } else {
      return 0;
    }
  } else if (document.getElementById("advanced").checked) {
    let result = confirm("Hey " + username + "! You have selected the advanced difficulty. Are you sure you wish to proceed?");
    if (result == true) {
      numberRand = 100;
    } else {
      return 0;
    }
  }


  for (let i = 0; i < questionList.length; i++) {
    let answer = parseInt(prompt("What is the answer to " + question));
    let correct = "<span style='background-color: #12CA00'>Your Answer to question </span> " + "<span  style='background-color: #12CA00'>" + i + "</span>" + "<span  style='background-color: #12CA00'> is correct</span>"
    let wrong = "<span style='background-color: #ca0002'>Your Answer to question </span> " + "<span  style='background-color: #ca0002'>" + i + "</span>" + "<span  style='background-color: #ca0002'> is wrong</span>"
    if (answer === eval(question)) {
      result.push(correct);
      question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
      total += 2;
    } else {
      result.push(wrong);
      question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);

    }
  }

  let display = result.join("</br>") + "</br>" + "You have got " + total + " marks";
  document.getElementById("result").innerHTML = display;
}
<div id="infoCol_main" class="infoCol_main">
  <script src="../Javascript/tute09.js"></script>
  <form id="form">
    <h1>Welcome</h1>
    <fieldset>
      <label>Please enter your name here: <br><input type="text" id="username"  name="username" required></label><br>
      <label>Please choose your difficulty level: <br>
                    <input type="radio" name="difficulty" id="beginner" value="Beginner"  required>Beginner<br>
                    <input type="radio" name="difficulty" id="intermediate" value="Intermediate" required>Intermediate<br>
                    <input type="radio" name="difficulty" id="advanced" value="Advanced" required>Advanced<br>
                </label>
      <div class="buttonHold">
        <input type="submit" onclick="MathRandom2()" value="Begin">
      </div>
    </fieldset>
  </form>
</div>
<div>
  <p id="result"></p>
</div>
0 голосов
/ 28 апреля 2019

Поведение ввода по умолчанию заключается в обновлении страницы после прохождения функции. Все, что вам нужно сделать, это добавить это в начало вашей функции:

function MathRandom2() {
    event.preventDefault();
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...