如何使用Jquery/Javascript将我的一个文件夹中的所有图像加载到我的网页中

ris*_*shy 46 html javascript jquery image

我在.js文件所在的目录中有一个名为"images"的文件夹.我想使用Jquery/Javascript将"images"文件夹中的所有图像加载到我的html页面中.

因为,图像的名称不是一些连续的整数,我怎么能加载这些图像?

Rok*_*jan 61

同时使用localhost和实时服务器,并允许您扩展允许的文件扩展名的分隔列表:

var folder = "images/";

$.ajax({
    url : folder,
    success: function (data) {
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                $("body").append( "<img src='"+ folder + val +"'>" );
            } 
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

基本上是对Roy的OA的改进

  • 在我的情况下不起作用 --- 在 Chrome 中给出错误:`file:///&lt;my_path&gt;/images/。仅协议方案支持跨源请求:http、data、chrome、chrome-extension、https、chrome-extension-resource。 (3认同)
  • 这应该是公认的答案。这是真正有效的完美解决方案。 (2认同)
  • @ RokoC.Buljan我无法让它发挥作用.我在我的html文件中使用这个脚本,在`<script> </ script>`标签内.有任何想法吗? (2认同)

Roy*_*M J 50

使用 :

var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
    //This will retrieve the contents of the folder if the folder is configured as 'browsable'
    url: dir,
    success: function (data) {
        //List all .png file names in the page
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location.host, "").replace("http://", "");
            $("body").append("<img src='" + dir + filename + "'>");
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

如果你有其他扩展,你可以使它成为一个数组,然后逐个使用in_array().

Ps:上面的源代码没有经过测试.

  • 这对我有用,但我从var filename中删除了.host.所以:`var filename = this.href.replace(window.location,"")` (2认同)
  • 而不是使用:contains,使用过滤器来测试多个扩展`.find("a").filter(function(){return regexp.test($(this).text());}).`定义regexp为`var regexp = new Regexp("\.png |\.jpg |\.gif");` (2认同)

Bar*_*tra 10

这是添加更多文件扩展的方法,在Roy MJ在本页顶部给出的示例中.

var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J   
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我添加了更多包含.


Pna*_*Wer 6

这是一种方法.涉及做一点PHP.

PHP部分:

$filenameArray = [];

$handle = opendir(dirname(realpath(__FILE__)).'/images/');
        while($file = readdir($handle)){
            if($file !== '.' && $file !== '..'){
                array_push($filenameArray, "images/$file");
            }
        }

echo json_encode($filenameArray);
Run Code Online (Sandbox Code Playgroud)

jQuery部分:

$.ajax({
            url: "getImages.php",
            dataType: "json",
            success: function (data) {

                $.each(data, function(i,filename) {
                    $('#imageDiv').prepend('<img src="'+ filename +'"><br>');
                });
            }
        });
Run Code Online (Sandbox Code Playgroud)

所以基本上你做一个PHP文件,将图像文件名列表作为JSON返回,使用ajax调用获取JSON,并将它们添加/附加到html.您可能希望过滤从文件夹中抓取的文件.

1开始对php部分提供了一些帮助


Rai*_*man 6

如果有兴趣在没有 jQuery 的情况下执行此操作 - 这是目前最受好评的答案的纯 JS 变体(来自此处):

var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
  if (xhr.status === 200) {
    var elements = xhr.response.getElementsByTagName("a");
    for (x of elements) {
      if ( x.href.match(/\.(jpe?g|png|gif)$/) ) { 
          let img = document.createElement("img");
          img.src = x.href;
          document.body.appendChild(img);
      } 
    };
  } 
  else {
    alert('Request failed. Returned status of ' + xhr.status);
  }
}
xhr.send()
Run Code Online (Sandbox Code Playgroud)