简体   繁体   中英

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">

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.

Look at this plunker I made with your code. By the way one ")" was missing after images.length https://plnkr.co/edit/mdyXsf5FoSPHOQGqCoO2?p=preview

var x = Math.floor((Math.random() * images.length)); $('#afbeelding').attr('src', images[x]);

Tell me if it's ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM