问题
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