javascript для отображения div - PullRequest
0 голосов
/ 17 июня 2020

код сценария, когда пользователь нажимает кнопку, отображается 1-й div (# 1-div), а при повторном нажатии отображается 2-й div (# 2-div) ... et c

Вот что я работали на данный момент:

'' '

<head>
    <style>
        #div-1, #div-2, #div-3{
          display: none;
          width: 100%;
          padding: 50px 0;
          text-align: center;
          background-color: lightblue;
          margin-top: 20px;
        }
    </style>
</head>

<body>
<form>
    <input type="text" id="number" value="0"/>
</form>
<p>What is the color of the ocean?</p>
<div id="div-1">
    <p>What is the color of the sky?</p>
</div>
<div id="div-2">
    <p>What is the color of the sand?</p>
</div>
<div id="div-3">
    <p>What is the color of the bus?</p>
</div>


<button onclick="nextQuestion()">Next Question</button>

<script>
function nextQuestion()
{

}
</script>

' ''

1 Ответ

4 голосов
/ 17 июня 2020

Запомните индекс текущего отображаемого элемента и увеличивайте его на +1 после каждого щелчка:

let question = document.querySelectorAll(".question");
let index = 0;

show(question[index]);

document.getElementById("next").addEventListener("click", function _tmp() {
  hide(question[index]);
  index++;
  
  if( !question[index] ) {
    this.removeEventListener("click", _tmp);
    this.textContent = "No more questions!";
    // this keyword refers to context of function call (here: The clicked button)
    return;
  }
  
  show(question[index]);
});

/***/
function show(el, value) {
  el.style.display = value || "block";
}
function hide(el) {
  el.style.display = "none";
}
.question {
  display: none;
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}
<button id="next">Next Question</button>
<hr>

<div class="question">
  <p>What is the color of the ocean?</p>
</div>
<div class="question">
  <p>What is the color of the sky?</p>
</div>
<div class="question">
  <p>What is the color of the sand?</p>
</div>
<div class="question">
  <p>What is the color of the bus?</p>
</div>

Ps Если пронумерованные идентификаторы, имена классов, переменные и т. Д. c. появляются в вашем коде, значит, что-то пошло не так) Попробуйте решить проблему более общим способом, с помощью циклов, массивов.

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