我一直在关注其他一些教程,并设法使图像与特定文本组合以在加载时显示,并在刷新后显示不同的图像和组合文本。
但是现在我想将其连接到一个按钮,这样文本和图像的随机组合仅在单击时显示,该按钮没有任何作用。
头部标记中的Javascript
<div id="quote"></div>
<input class="Randombutton" style="float: left;" type="button"
value="Randomize" onclick="randomImg()">
<script>
(function randomImg() {
var quotes = [
{
text: "BIO1",
img: "images/captainamerica.jpg"
},
{
text: "BIO2",
img: "images/hulk.jpg",
},
{
text: "BIO3",
img: "images/spiderman.jpg",
},
{
text: "BIO4",
img: "images/blackwidow.jpg",
},
{
text: "BIO5",
img: "images/ironman.png",
},
];
var quote = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("quote").innerHTML =
'<p>' + quote.text + '</p>' +
'<img src="' + quote.img + '">';
})();
</script>
非常感谢您的帮助。谢谢。
答案 0 :(得分:1)
这符合您的需求吗?
function randomImg() {
var quotes = [
{
text: "BIO1",
img: "images/captainamerica.jpg"
},
{
text: "BIO2",
img: "images/hulk.jpg",
},
{
text: "BIO3",
img: "images/spiderman.jpg",
},
{
text: "BIO4",
img: "images/blackwidow.jpg",
},
{
text: "BIO5",
img: "images/ironman.png",
},
];
var quote = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("quote").innerHTML =
'<p>' + quote.text + '</p>' +
'<img src="' + quote.img + '">';
}
<div id="quote"></div>
<input class="Randombutton" style="float: left;" type="button"
value="Randomize" onclick="randomImg()">