javascript 如何使用 jQuery 计算目录中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11489738/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:23:55  来源:igfitidea点击:

How do I count files in a directory using jQuery?

phpjavascriptjquery

提问by bdrelling

I'd like to count the number of files in a folder and return that number to set a variable in a .js file.

我想计算文件夹中的文件数并返回该数字以在 .js 文件中设置变量。

Essentially, I have X number of images in a folder. When the user clicks the right arrow, I replace the existing set of 8 images with the next set of 8 images, and so on and so forth. I currently manually enter the variable (38 right now) into the page, since there are 38 thumbnails in the folder.

本质上,我在一个文件夹中有 X 个图像。当用户单击右箭头时,我用下一组 8 张图像替换现有的一组 8 张图像,依此类推。我目前在页面中手动输入变量(现在是 38 个),因为文件夹中有 38 个缩略图。

The code works perfectly, but I hate the idea of changing a number each time I add a file. I'd like to have it set the variable to the exact number of images in the folder.

该代码运行良好,但我讨厌每次添加文件时更改数字的想法。我想让它将该变量设置为文件夹中图像的确切数量。

Is this possible using JavaScript or jQuery? Do I need to write a PHP file to do return this variable for me? Any information would be great!

这可以使用 JavaScript 或 jQuery 吗?我是否需要编写一个 PHP 文件来为我返回这个变量?任何信息都会很棒!

回答by Mendhak

This is the kind of task PHP is better suited for, keep your Javascript to the client-side. Write a very simple PHP script that counts the files in a folder

这是 PHP 更适合的任务,将您的 Javascript 保留在客户端。编写一个非常简单的 PHP 脚本来计算文件夹中的文件数

echo iterator_count(new DirectoryIterator('/home/path/dir'));

And call it from your JQuery script.

并从您的 JQuery 脚本中调用它。

$.get('numberoffiles.php', function(data) {
  alert(data);
});

回答by mplungjan

If you must use client side and the files are numbered, preload the file and set the number when you get an error

如果必须使用客户端并且文件已编号,请预加载文件并在出现错误时设置编号

...
Img = new Image();
Img.onerror=function() {
  maxImages=cnt-1;
}
Img.src = "image_"+cnt+".jpg";

回答by Oscar Jara

Simple way:

简单的方法:

<?php
    $dir = "images";
    $file_count = count(glob("{$dir}/*.*"));
?>
<html>
<head>
<title>Welcome</title>
</head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 

    var dir = <?php echo $dir ?>;
    var file_count = <?php echo $file_count ?>;

    $('#msg').html('File count in folder ' + dir + ' is ' + file_count);
});
</script>
<body>
<div id="msg"></div>
</body>
</html>

回答by Adam F

I would do it like this

我会这样做

echo count(glob("{$_GET['dir']}/*.*"));