javascript jquery中的“任何”布尔函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16576560/
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
"Any" boolean function in jquery
提问by Wilson
Is there any easyway to check if any elements in a jquery selector fulfill a condition? For instance, to check if any textboxes in a form are empty (kind of pseudo, not real jquery):
有什么简单的方法可以检查 jquery 选择器中的任何元素是否满足条件?例如,要检查表单中的任何文本框是否为空(伪类,而不是真正的 jquery):
$('input.tb').any(val().length == 0);
Note: I know it could be done with a helper method, just curious if it was possible in one statement.
注意:我知道可以使用辅助方法来完成,只是好奇是否可以在一个语句中实现。
回答by KyleMit
The problem with the current answers and also jQuery's own filtering functions, including .is()
, .has()
, and .filter()
is that none of them short circuitas soon as the criteria is met. This may or may not be a large performance concerndepending on how many elements you need to evaluate.
与目前的答案,也是问题jQuery的自己的过滤功能,包括 .is()
,.has()
,和.filter()
是他们没有短路,一旦条件满足。这可能是也可能不是一个大的性能问题,具体取决于您需要评估的元素数量。
Here's a simple extension method that iterates through a jQuery object and evaluates each element so we can early terminate as soon as we match the criteria.
这是一个简单的扩展方法,它遍历一个 jQuery 对象并评估每个元素,这样我们就可以在匹配条件时尽早终止。
jQuery.fn.any = function(filter){
for (i=0 ; i<this.length ; i++) {
if (filter.call(this[i])) return true;
}
return false;
};
Then use it like this:
然后像这样使用它:
var someEmpty= $(":input").any(function() {
return this.value == '';
});
This yields much better perf results:
这会产生更好的性能结果:
If you do go the pure jQuery route, $.is(<sel>)
is the same as!!$.filter(<sel>).length
so it probably makes for shorter and more imperative code to use is
instead of filter
.
如果你去纯粹的jQuery的路线,是一样的所以它可能使得对更短,更迫切的代码来使用,而不是。$.is(<sel>)
!!$.filter(<sel>).length
is
filter
Here's an example of $.any()
in action:
下面是一个$.any()
在行动的例子:
jQuery.fn.any = function(filter){
for (i=0 ; i<this.length ; i++) {
if (filter.call(this[i])) return true;
}
return false;
};
$(function() {
$(":input").change(function() {
var someEmpty = $(":input").any(function() {
return this.value == '';
});
console.log("Some Empty:", someEmpty);
}).eq(0).change(); // fire once on init
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
Further Reading:
进一步阅读:
回答by Malk
jQuery has a lot of pseudo selectors built in: http://api.jquery.com/category/selectors/jquery-selector-extensions/
jQuery 内置了很多伪选择器:http: //api.jquery.com/category/selectors/jquery-selector-extensions/
You can also build your own with the filter()
function: http://api.jquery.com/filter/
您还可以使用以下filter()
功能构建自己的功能:http: //api.jquery.com/filter/
$('input.tb').filter(function() { return this.value.length == 0});
回答by Rhys van der Waerden
.is()
with a function argument is what you're after.
.is()
带有函数参数就是你所追求的。
var anyEmpty = $('input.tb').is(function(index, element) {
return !element.value;
})
WARNING:
警告:
This function is surprising in that it doesn't short circuit. It will needlessly iterate through all selected elements, even if the callback has already been satisfied.
这个功能令人惊讶,因为它不会短路。即使回调已经被满足,它也会不必要地遍历所有选定的元素。
let i = 0
let result = $('div').is((index, element) => {
i++;
return element.tagName === 'DIV';
})
console.log(`count = ${i}, result = ${result}`);
// count = 732, result = true
回答by Brent
I am adding this a year late for others who stumble across this:
对于偶然发现此问题的其他人,我晚了一年添加此内容:
Malk's answer will fulfill the EXACT requirements in your example with:
马尔克的回答将满足您示例中的确切要求:
$('input.tb').filter(function() { return this.value.length == 0}).length != 0;
A slightly more performant way of doing this (if the condition is met early, the filter function will still iterate over the remaining DOM elements) would be to write your own helper method (which, admittedly, the op has stated
执行此操作的一种稍微高效的方法(如果条件提前满足,过滤器函数仍将迭代剩余的 DOM 元素)是编写您自己的辅助方法(无可否认,操作已声明
I know it could be done with a helper method, just curious if it was possible in one statement
我知道这可以通过辅助方法完成,只是好奇是否可以在一个语句中实现
, but I came to this page hoping to save 2 mins writing my own):
,但我来到这个页面希望能节省 2 分钟写我自己的时间):
;(function($) {
//iterates over all DOM elements within jQuery object
//and returns true if any value returned from the supplied function is 'truthy'.
//if no truthy values are returned, returns false.
//
//Function( Integer index, Element element )
$.fn.any = function(fn) {
var i=0;
for (;i<this.length;i++) {
if (fn.call(this[i],i,this[i])) {return true;}
}
return false;
}
)(jQuery);
回答by adeneo
if ( $('input.tb[value=""]').length > 0 ) // there are empty elements