[英]Jquery/Javascript: Display a random image from an array by pressing a button
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:
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];
}
注意:未經測試。 另外,您在數組末尾有一個空條目,因此我將其修復。
看看我用您的代碼制作的這個插件。 順便說一句,images.length https://plnkr.co/edit/mdyXsf5FoSPHOQGqCoO2?p=preview之后缺少一個“)”
var x = Math.floor((Math.random() * images.length)); $('#afbeelding').attr('src', images[x]);
告訴我是否可以
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.