【发布时间】: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)会给你一个从0到4的号码。 -
innerHTML方法需要string,而不是Array。只需更改document.getElementById("result").innerHTML = randomParagraph; -
@ElChiniNet 我认为,你错了。应该是
document.getElementById("result").innerHTML = idArray[randomParagraph] -
@Syntac 是的,你是对的。我没有注意到
randomParagraph是一个整数。 -
@ElChiniNet 你想改变它,我删除我的评论?
标签: javascript event-listener buttonclick