javascript 在 jquery 中检查某些输入类型文件是否为空的更好方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17044211/
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
Better way to check if some inputs type file is empty in jquery?
提问by Snake Eyes
I know that is simple question but I need an advice from experienced people.
我知道这是一个简单的问题,但我需要有经验的人的建议。
I have 3 input type file like:
我有 3 个输入类型文件,例如:
<input type="file" name="1-files" />
<input type="file" name="2-files" />
<input type="file" name="3-files" />
I select all inputs (on my page I have also other inputs type file) which name ends with "-files" ( I wrote in Google Chrome console):
我选择所有输入(在我的页面上我还有其他输入类型文件),其名称以“-files”结尾(我在谷歌浏览器控制台中写的):
$("input[type='file'][name*='-files']").length
Ok. I select a file using 1-files
input. After that, I run the following code in Google Chrome console:
行。我使用1-files
输入选择一个文件。之后,我在 Google Chrome 控制台中运行以下代码:
$("input[type='file'][name*='-files']:empty").length
I expect to be 2
but appears 3
.
我希望是2
但出现3
。
Can you tell me why ?
你能告诉我为什么吗 ?
I want to get all elements of input type file which values are empty. I used in short way the selector :empty
but it seems not working properly.
我想获取值为空的输入类型文件的所有元素。我以简短的方式使用了选择器,:empty
但它似乎无法正常工作。
Of course, I could use
当然,我可以用
var empty_count = 0;
$.each($("input[type='file'][name*='-files']"), function(k, v){
if($(this).val() === '')
empty_count++;
});
But I want the shortest way to do this without $.each
.
但我想要最短的方法来做到这一点,而不需要$.each
.
Thank you
谢谢
采纳答案by David says reinstate Monica
It matches three because :empty
matches an element with no descendants, and am input element by definition cannot have descendants (so all are empty, and therefore match the :empty
selector).
它匹配三个因为:empty
匹配一个没有后代的元素,并且 am input 元素根据定义不能有后代(所以都是空的,因此匹配:empty
选择器)。
To find those elements without selected files, I'd suggest:
要在没有选定文件的情况下找到那些元素,我建议:
$("input[type='file'][name*='-files']").filter(function (){
return !this.value
}).length;
References:
参考:
回答by bipen
you can use filter
insted of $.each
..
你可以使用filter
insted的的$.each
..
$("input[type='file'][name*='-files']").filter(function(k){
return $(this).val() === '';
}).length;
回答by vanessen
consider the following codes, i always used this :
考虑以下代码,我总是使用这个:
$("input[type='file'][name*='-files']").each(function(){
if($(this).val().length == 0){
alert("field is empty");
}
});