jQuery/Javascript:按下按钮即可显示数组中的随机图像 [英] Jquery/Javascript: Display a random image from an array by pressing a button
本文介绍了jQuery/Javascript:按下按钮即可显示数组中的随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var images = ["https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Playing_card_heart_5.svg/200px-Playing_card_heart_5.svg.png", "http://www.pandasecurity.com/mediacenter/src/uploads/2014/11/short-link.jpg", ];
function myFunction() {
var x = Math.floor((Math.random() * images.length); $('#afbeelding').attr('src', images[x]);
}
HTML:
<button onclick="myFunction()">Try it</button>
<img id="afbeelding">
推荐答案
有许多可能的原因导致此问题,但最有可能的原因是您可能尚未安装JQuery.实际上,您甚至不需要JQuery:
There are many possible causes of this problem, but the most likely is that you may not have installed JQuery. In fact, you don't even need JQuery for this:
var images = ["https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Playing_card_heart_5.svg/200px-Playing_card_heart_5.svg.png", "http://www.pandasecurity.com/mediacenter/src/uploads/2014/11/short-link.jpg"];
function myFunction() {
var x = Math.floor((Math.random() * images.length));
document.getElementById('afbeelding').src = images[x];
}
注意:未经测试. 另外,您在数组末尾有一个空条目,因此我将其修复.
Note: Untested. Also, you had a null entry at the end of your array, so I fixed that.
这篇关于jQuery/Javascript:按下按钮即可显示数组中的随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文