【问题标题】:How to display randomly text when a button is clicked单击按钮时如何随机显示文本
【发布时间】:2017-12-10 03:34:33
【问题描述】:

我有一个项目要做,但我被困在这个阶段。我有 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>

【问题讨论】:

  • 你为什么从1开始索引? Math.floor(Math.random()*5) 会给你一个从 04 的号码。
  • innerHTML 方法需要 string,而不是 Array。只需更改document.getElementById("result").innerHTML = randomParagraph;
  • @ElChiniNet 我认为,你错了。应该是document.getElementById("result").innerHTML = idArray[randomParagraph]
  • @Syntac 是的,你是对的。我没有注意到randomParagraph是一个整数。
  • @ElChiniNet 你想改变它,我删除我的评论?

标签: javascript event-listener buttonclick


【解决方案1】:

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>

【讨论】:

    【解决方案2】:

    缩短

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-11
      • 2016-09-11
      • 2018-01-17
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多