Display 3 random images in Javascript from an java

2019-08-07 02:48发布

问题:

I am struggling to take 3 random images (No repeat) out of my Javascript array and print them on screen within separate Divs.

My Javascript array is being populated by a database which contains the links/location of the images on the server.

Currently my page looks like this:

<html>
   <head>
  </head>
   <body>
    <div></div>
    <script>
      var items = [
      {name:'Coch',image:'upload/coch.png'},{name:'Glas',image:'upload/glas.png'},     {name:'Melyn',image:'upload/melyn.png'},{name:'Ci',image:'upload/dog.jpg'},    {name:'Cath',image:'upload/cath.jpg'},{name:'Gwyrdd',image:'upload/gwyrdd.png'},{name:'Un',image:'upload/un.jpg'},{name:'Dau',image:'upload/dau.jpg'},{name:'Tri',image:'upload/tri.jpg'},{name:'Bochdew',image:'upload/bochdew.jpg'},{name:'Piws',image:'upload/piws.png'}      ];
      for (var i = 0; i < items.length; i += 1) {
        document.getElementsByTagName('div')[0].innerHTML += items[i].name + " / " +       items[i].image + "<br />\n";
      } 
    </script>
  </body>
</html>

This code simply takes the image links from the database and inserts them into a javascipt array. (And prints the links on screen at the moment)

Can anyone give me any help on how to get this to work? Take 3 random images links from that array (No duplication's), and display the 3 images on screen in 3 different divs.

I am not good with javascipt at all and any code examples would be great.

Thank You in advance for any replies.

回答1:

Shuffle your array and then take the first three items. Here you can find a nice function to shuffle arrays: How to randomize (shuffle) a JavaScript array?



回答2:

Assuming the links to the image sources are correct relative to the page that the images will be on, this should do the trick:

var list = document.getElementsByTagName('div')[0];
for(i = 0; i < 3; i++) {
  // Choose a random item and remove it from the array
  var item = items.splice(Math.floor(Math.random() * items.length), 1)[0];

  // Create the image element and set its src attribute
  var image = document.createElement('img');
  image.src = item.image;

  // Add it to your container element
  list.appendChild(image);
}

Note that this will modify the 'items' array, so if you need it later you will need to copy the array first or tweak the logic.

JSFiddle: http://jsfiddle.net/ynhCN/1/