我有一个项目要做,我在这个阶段陷入困境。我有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>
答案 0 :(得分:0)
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];
}
&#13;
<body>
<button onclick="myFunction()" id="select">Pick text</button>
<div class="main">
<p id="result"></p>
</div>
<footer class="footer">Hey</footer>
</body>
&#13;
答案 1 :(得分:0)
<强>缩短强>
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)];
}
&#13;
<body>
<button id="select">Pick text</button>
<div class="main">
<p id="result"></p>
</div>
<footer class="footer">Footer</footer>
</body>
&#13;