Getting images from folder with for jQuery slideshow

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 02:20:02

问题


My Jquery slideshow script looks like that

  $(function() {
    $('#bg').crossSlide({
      sleep: 3,
      shuffle: true,
      fade: 1
    }, [
  { src: 'core/design/images/bgs/1.jpg'},
  { src: 'core/design/images/bgs/2.jpg'},
  { src: 'core/design/images/bgs/3.jpg'},
  { src: 'core/design/images/bgs/4.jpg'}
    ])
  });

As you see, I declared the images' paths one by one. Is there any way to scan folder for images and add all at once. Maybe, it can be done with PHP?


回答1:


It cannot be done with Javascript. But with a embedded server side code it should be possible (like PHP). Here is an example in php.

There exists a function called glob, which might be suitable for your purpose. Here is an example of how to use it.

$path = <absolute path for the folder where images are located>
$images = glob($path.'/*.jpg') // this returns an array of file names only doesnt contain the path

Now you have the list of arrays in php. You have to start using this in javascript

$(function() {
$('#bg').crossSlide({
  sleep: 3,
  shuffle: true,
  fade: 1
}, [
<?php foreach($images as $filename){ ?>
    { src: 'core/design/images/bgs/<?php echo $filename.jpg ?>'},
<? } ?>

    ])
  });



回答2:


Yes. It can be done using JS / jQuery:

Works both locally and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:

var folder = "core/design/images/bgs/";

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

in your case you want to construct an array of Objects {src:"path"} so it could look like:

var folder = "core/design/images/bgs/";

$.ajax({
    url : folder,
    success: function (data) {
        var srcArr = [];
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.jpg|\.png|\.gif/) ) { 
                var ob = {src : folder+val};
                srcArr.push( ob );
            } 
        });
        // Now that the Array is filled with Objects send to callback
        readFolderCallback( srcArr );
    }
});


function readFolderCallback( srcArr ) {
    $('#bg').crossSlide({
      sleep: 3,
      shuffle: true,
      fade: 1
    }, arrSrc);
}

https://stackoverflow.com/a/32940532/383904



来源:https://stackoverflow.com/questions/8031951/getting-images-from-folder-with-for-jquery-slideshow

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