这里有一个小 sn-p 来检查你所有的 text inputs 是否为空:
var isEmpty = $("input[type='text']").filter(function () {
return this.value.trim();
}).length === 0;
console.log( isEmpty ); // boolean true/false
jsBin playground
P.S:checkbox 和 radio 游戏更简单:
var isUnchecked = $("input[type='checkbox']:checked").length === 0;
var isRadioUnchecked = $("input[type='radio']:checked").length === 0;
奖励::blank 自定义选择器(适用于任何元素)
jQuery.extend(jQuery.expr[':'], {
blank: function(e,i,m) {
if(/input|textarea/i.test(e.tagName)) {
if(/checkbox|radio/i.test(e.type)){
return !e.checked;
}else{
return !e.value.length;
}
}else{
return !e.innerHTML.trim();
}
}
});
$("div:blank").css({outline:"2px solid red"});
$("input:blank").css({outline:"2px solid red"});
$("textarea:blank").css({outline:"2px solid red"});
$("div:not(:blank)").css({outline:"2px solid green"}); // how cool is that? Using :not
*{margin:5px;padding:2px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div>Example using :not(:blank) selectors</div>
<input type="text" value="abc">
<input type="text" value="">
<input type="checkbox">
<input type="checkbox" checked>
<input type="radio" checked>
<input type="radio">
<textarea></textarea>
<textarea>abc</textarea>
在<div> 或<p> 等标准元素上,:blank 的行为与 jQuery 的 :empty 选择器不同,请注意空格和换行符:
<p>
</p>
并查看结果:
$("p:blank").length // 1 (found one blank paragraph)
$("p:empty").length // 0 there's no empty paragraph (since the newlines/spaces)
回到你的问题 :)
由于您循环所有元素,目前您只需将isEmpty 的值设置为循环中的最后一个元素 - 值。
您可以将您的布尔标志声明到 if 中,例如:
var isEmpty = false; // start with a falsy presumption
$('input').each(function(){
// as long as `isEmpty` is `false`
if(isEmpty===false && $.trim( this.value ) === "") {
isEmpty = true;
}
});
另外,检查 emptiness 执行 === "" 更有意义返回 true
否则反过来就是反转你的否定
var isEmpty = true; // start with a truthy presumption
$('input').each(function(){
if(isEmpty && $.trim( this.value )){
isEmpty = false;
}
});
这是一个活生生的例子:
var isEmpty = true; // start with a truthy presumption
$('input').each(function(){
if(isEmpty && $.trim( this.value )){
isEmpty = false;
}
});
alert(isEmpty); // false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="">
<input type="text" value="something">
<input type="text" value="">