如何使用Jquery从我的Image目录中随机加载单个图像? [英] How can I randomly load a single image from my Image directory using Jquery?

查看:104
本文介绍了如何使用Jquery从我的Image目录中随机加载单个图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Jquery / Javascript的新手,我想从我的图片目录中将一张图片加载到我的主页上,以便在刷新新的随机图片时出现。有没有办法让Jquery只是访问我的图像文件夹并随机加载任何图像?我目前正在使用一个JS代码,要求我输入我想要加载的每个图像名称。这是详尽的,虽然我可能对Jquery知之甚少,但我认为这可以以更清洁的方式完成。如果我天真,我会提前道歉。

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.

推荐答案

当您在HTML标记中链接到它们时,您可以使用js函数中的相同链接如此链接到它们。

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


      • script.js

      您只需链接到 images / image1.jpg

      < header> 标记中添加:

      <script type="text/js" src="js/script.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

      这篇关于如何使用Jquery从我的Image目录中随机加载单个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆