javascript number of images
javascript number of images
我有一个小的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中运行。
相关文章:
- HighChart : Usage of setData
- document.images未加载在chrome或firefox上,但已加载在IE上
- Difference between methods of defining JavaScript 'class
- 为什么我在下面的..of循环中得到意外令牌
- Appending the innerhtml of <th>
- Animation cuts off multiple lines of text in <p>
- javascript: functionname() instread of functionname()
- jQuery使用.of()删除事件处理程序时出现的问题
- Three.js issue creating meshes outside of loader's load(
- jquery in the middle of html
- JavaScript equivalent of C#'s DynamicObject?
- nodejs console.log of object
- value of jquery sortable
- Javascript imageData returns array of 0's
- 对于grunt构建中的(let.of)错误
- Opposite of jQuery's :eq()
- Implementation of jQuery 'animate' with Meteor
- 当调用.of()然后调用.on()时,Jquery是否可能将事件推迟
- javascript number of images
- Krajee 引导程序文件输入 maxFileCount of Images.