计算空文件上传控件

Count empty file upload controls

本文关键字:控件 文件 计算      更新时间:2023-09-26

在一组动态生成的文件上传控件中:

<input type="file" name="archivos[]">
<input type="file" name="archivos[]">
<input type="file" name="archivos[]">
// ...

。我可以很容易地数出非空的:

// Works fine
var nonEmptyCount = $("input[type='file'][name='archivos[]'][value!='']").length;

但是,当我尝试计算的(我实际需要的)时,选择器永远不会匹配任何内容:

// Always zero
var emptyCount = $("input[type='file'][name='archivos[]'][value='']").length;

我不敢相信我需要这个繁琐的代码:

// Works but ugly
var emptyCount = $("input[type='file'][name='archivos[]']").length -
    $("input[type='file'][name='archivos[]'][value!='']").length;

我错过了哪一点?

一种解决方案是检查迭代器中的值是否为空,例如:

$("#findEmpty").on("click", function() {
  var count = 0;
  $(":file[name='archivos[]']").each(function() {
    if (this.value == "") {
      count++;
    }
  });
  alert(count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="archivos[]" />
<input type="file" name="archivos[]" />
<input type="file" name="archivos[]" />
<input type="file" name="archivos[]" />
<input type="file" name="archivos[]" />
<input type="file" name="archivos[]" />
<input type='button' value='Check Empty' id='findEmpty' />

您可以

通过以下方式过滤它们:

var emptyOne = $("input[type='file'][name='archivos[]']").filter(function () {
        return $(this).val() == "";
    });

$(function () {
    var emptyOne = $("input[type='file'][name='archivos[]']").filter(function () {
        return $(this).val() == "";
    });
    alert(emptyOne.length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input type="file" name="archivos[]">
<input type="file" name="archivos[]">
<input type="file" name="archivos[]">

示例小提琴

我没有

解释(我会立即接受任何提供解释的答案),但根本原因似乎是使用通用属性等于选择器来查找控件:

$("input[type='file']")

如果我使用 jQuery 扩展快捷方式,其他一切都按预期工作:

$("input:file")

根据文档:

  • 两个选择器的行为应该相同
  • [type='file']应该表现得更好

。所以某处一定有错误。