Как отображать случайный текст при нажатии кнопки

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

function myFunction() {
  idArray = new Array()
  idArray [1] = "First paragraph text"
  idArray [2] = "Second paragraph text
  idArray [3] = "Third paragraph text
  idArray [4] = "Fourth paragraph text"
  idArray [5] = "Fifth paragraph text"

  document.getElementById("select").onclick = myFunction;
  randomParagraph = Math.floor(Math.random()*5);

  document.getElementById("result").innerHTML = new Array[randomParagraph];       
}
<body>
  <button onclick="myFunction()" id="select">Pick text</button>

  <div class="main">
    <p id="result"></p>
  </div>
  <footer class="footer">Hey</footer>
</body>

2 ответа

new Array[randomParagraph]; не работает.

Что вам нужно сделать, это получить доступ к значению в индексе формы idArray - idArray[randomParagraph + 1]

+1 нужно было добавить, поскольку определенный вами массив idArray переходит от 1 до 5, а сгенерированное случайное число - от 0 до 4, так как вы используете Math.floor

Рабочий пример здесь:

function myFunction() {
  idArray = new Array()
  idArray [1] = "First paragraph text"
  idArray [2] = "Second paragraph text"
  idArray [3] = "Third paragraph text"
  idArray [4] = "Fourth paragraph text"
  idArray [5] = "Fifth paragraph text"

  document.getElementById("select").onclick = myFunction;
  randomParagraph = Math.floor(Math.random()*5);

  document.getElementById("result").innerHTML = idArray[randomParagraph + 1];       
}
<body>
  <button onclick="myFunction()" id="select">Pick text</button>
  <div class="main">
    <p id="result"></p>
  </div>
  <footer class="footer">Hey</footer>
</body>

укороченный

var text = [
  "First paragraph text",
  "Second paragraph text",
  "Third paragraph text",
  "Fourth paragraph text",
  "Fifth paragraph text"
];

document.getElementById("select").onclick = function() {
  document.getElementById("result").innerHTML = text[Math.floor(Math.random() * text.length)];
}
<body>
  <button id="select">Pick text</button>
  <div class="main">
    <p id="result"></p>
  </div>
  <footer class="footer">Footer</footer>
</body>

Другие вопросы по тегам