很容易做循环,但我想知道是否有一种方法来查看集合中的每个项目是否匹配没有循环的条件。例如:jquery测试一个条件与整个集合没有循环
if($('.many-items-of-this-class').hasClass('some-other-class')) { }
如果集合中的任何项返回true,则返回true。有没有办法做这种操作,所以只有当所有项都为真时才返回true?
很容易做循环,但我想知道是否有一种方法来查看集合中的每个项目是否匹配没有循环的条件。例如:jquery测试一个条件与整个集合没有循环
if($('.many-items-of-this-class').hasClass('some-other-class')) { }
如果集合中的任何项返回true,则返回true。有没有办法做这种操作,所以只有当所有项都为真时才返回true?
您可以缓存该设置,然后针对测试其他类的设备运行过滤器,并比较两者的属性。
var many_items = $('.many-items-of-this-class');
if(many_items.length === many_items.filter('.some-other-class').length) { }
或更短,但可以说较为混乱,你可以使用一个.not()
滤波器.length
和!
。
var many_items = $('.many-items-of-this-class');
if(!many_items.not('.some-other-class').length) { }
var $many = $('.many-items-of-this-class');
if (many.filter('.some-other-class').length == $many.length)
{
// all items have the class.
}
也许?其他选项是自己制作Selector。例如
.many-items-of-this-class:and(.some-other-class)
什么的。
检查它的目标是什么?如果您正在执行的操作,那么你可以通过chaining the selector检查这两个班在一次:
$('.many-items-of-this-class.some-other-class').each(
function(index, value) {
// Do stuff here
});
这并不比较(或检查)与_class A_ **所有项目也**已应用_class B_。 – 2011-06-09 17:41:59
@Brad:它没有--jQuery选择器检索同时应用了类A和类B的所有项目。当然,如果您需要检查所有_class A_是否仅仅为了检查而应用_class B_,那么是的,这不是最好的方法。 – voithos 2011-06-09 17:45:08
我把它作为后面的任务来读取(确保每个带有_class A_的项目都有一个_class B_应用于它(不仅仅是相交的项目)。 – 2011-06-09 17:47:20
if(! $('.many-items-of-this-class').is(':not(.some-other-class)')) { }
或者,如果集合是基于一个选择,只需
if($('.many-items-of-this-class:not(some-other-class)').length == 0) { }
if($('.many-items-of-this-class :not(.some-other-class)').size() == 0) {
// ...
}
您可以轻松编写一个插件来扩展每个功能。
(function($){
$.fn.allMustPassTest = function(test,params) {
var allPass = true;
$(this).each(function(){
if(!test.apply($(this),params)){
allPass = false;
}
});
return allPass;
};
})(jQuery);
与应用,例如:
var allPass = $('.many-items-of-this-class').allMustPassTest(function(){
return $(this).hasClass('some-other-class');
});
if(allPass){
//code to execute if all items have .some-other-class
}
或者另一种方式:
var hasClassTest = function(clazz){
return $(this).hasClass(clazz);
};
if($('.many-items-of-this-class').allMustPassTest(hasClassTest,['some-other-class'])){
}
德勤与过滤,脑屁了一会儿。 - 编辑:正在思考'地图',然后使用'上下文'。我从来没有想过过滤器存在! ; p – 2011-06-09 17:40:18