javascript number of images

javascript number of images

本文关键字:images of number javascript      更新时间:2023-09-26

我有一个小的html文件供个人使用,没有css、php或web服务器。我有一个文件夹"imgs"(与.html在同一文件夹中),其中包含名为image0.png、image1.png、image_2.png的图像…(所有图像都按顺序排列,直到没有图像为止)。我如何制作一个返回该文件夹中图像数量的javascript函数?

使用客户端JavaScript无法立即获取图像文件的数量,最好尝试逐个检索图像,直到出现404错误。

您可以使用img元素的onerror方法来检测请求的图像何时不存在——如果您请求的图像不存在,就会调用此方法。

这个问题可能很有用,它包含了一些您可以使用的示例代码。

通常的策略是按顺序将每个文件加载为映像,直到请求失败,并触发onerror回调。每个后续的图像获取都作为前一个图像的onload处理程序被触发。

// takes a callback that expects a single argument
function getImageCount(callback) {
    imageCounter(0);
    // pseduo-recursive function nested in the closure of the outer function
    // (nested so `callback` is always accessible without constantly passing it)
    function imageCounter(i) {
        var img = new Image();
        // if this failed, so the final image was the previous one
        img.onerror = function() { callback(i); }
        // if this succeeded, try the next one
        img.onload = function() { imageCounter(i + 1); }
        img.src = "image"+i+".png";
    }
}
// actually run it, with callback function that gets the count
getImageCount(function(count) {
    alert("There are " + count + "images.");
});

由于file: URL的同源策略受到限制,如果没有--allow-file-access-from-files命令行标志,这将无法在Chrome上运行,并且只有在从当前页面的同一目录或子目录提取图像时,它才能在Firefox中运行。