How can I randomly load a single image from my Image directory using Jquery?

懵懂的女人 提交于 2019-12-11 11:36:17

问题


I'm very new to Jquery/Javascript and I'd like to load a single image onto my homepage from my image directory so that upon refreshing a new random image appears. Is there a way for Jquery to simply access my images folder and load any image at random? I am currently using a JS code that requires I type each image name that I would like loaded. This is exhaustive and while I may not know much about Jquery, I think this can be done in a cleaner fashion. my apologies in advance if i'm being naive.


回答1:


When you link to the them in your HTML markup you can use the same link in a js function to link to them like so.

Not sure how your directory structure is set up but as an example.

  • dir
    • images
      • image1.jpg
    • scripts
      • script.js
    • style
    • index.html

in your js file you can just link to images/image1.jpg

in the <header> tag add:

<script type="text/js" src="js/script.js" />

Then in your script.js file do one of these:

//Raw Javascript

  function changeMe()
  {
    document.getElementById("changeMe").src = "images/" + getRandomImage();
  }

  <img id="changeMe" onLoad="changeMe()" src="images/default.jpg" />


 //JQuery
  $(document).ready(function(){
    $("#changeMe").src("images/" + getRandomImage());
  });
  <img id="changeMe" src="images/default.jpg" />

Then all you need to do is write the function that will return a random image from that directory. There are tons of ways to do this but for simplicity.

function getRandomImage() {
  var images = ["image1.jpg","image2.jpg","image3.jpg"];

  return images[Math.floor(Math.random() * images.length)];
}

JSFiddle



来源:https://stackoverflow.com/questions/27952820/how-can-i-randomly-load-a-single-image-from-my-image-directory-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!