JavaScript:如何加载文件夹中的所有图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11144261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: how to load all images in a folder?
提问by MaiaVictor
var img = new Image();
img.src = "images/myFolder/myImage.png";
The above will only load myImage.png. How to load all images of myFolder?
以上只会加载 myImage.png。如何加载 myFolder 的所有图像?
采纳答案by tskuzzy
JavaScript can't directly access the contents of a file system. You'll have to pass the contents using a server-side script (written in PHP, etc) first.
JavaScript 不能直接访问文件系统的内容。您必须首先使用服务器端脚本(用 PHP 等编写)传递内容。
Then once you have that, you can use a loop in your JavaScript to load them individually.
然后一旦你有了它,你就可以在你的 JavaScript 中使用一个循环来单独加载它们。
回答by Yuriy Galanter
If your image names are sequential like your said, you can create a loop for the names, checking at every iteration if image exists - and if it doesn't - break the loop:
如果您的图像名称像您所说的那样连续,您可以为名称创建一个循环,在每次迭代时检查图像是否存在 - 如果不存在 - 打破循环:
var bCheckEnabled = true;
var bFinishCheck = false;
var img;
var imgArray = new Array();
var i = 0;
var myInterval = setInterval(loadImage, 1);
function loadImage() {
if (bFinishCheck) {
clearInterval(myInterval);
alert('Loaded ' + i + ' image(s)!)');
return;
}
if (bCheckEnabled) {
bCheckEnabled = false;
img = new Image();
img.onload = fExists;
img.onerror = fDoesntExist;
img.src = 'images/myFolder/' + i + '.png';
}
}
function fExists() {
imgArray.push(img);
i++;
bCheckEnabled = true;
}
function fDoesntExist() {
bFinishCheck = true;
}
回答by Niet the Dark Absol
You need some way to get the list of files in that folder. This can either be defined manually as an array, or retrieved by an AJAX request to a server-side script that lists the files for you. Either way, there no "magic" method to get all the images in a folder.
您需要某种方式来获取该文件夹中的文件列表。这可以手动定义为数组,也可以通过 AJAX 请求检索到服务器端脚本,该脚本为您列出文件。无论哪种方式,都没有“神奇”的方法来获取文件夹中的所有图像。
回答by peacemaker
If you have all the names of the files in the folder, you'll need to loop through and open each image by name. You can't just load the whole folder directly and you can't access the file system in Javascript to get the names, you'll need to pass them to the page via something like PHP.
如果您拥有文件夹中所有文件的名称,则需要循环遍历并按名称打开每个图像。您不能直接加载整个文件夹,也不能在 Javascript 中访问文件系统来获取名称,您需要通过诸如 PHP 之类的东西将它们传递到页面。