如何检查任何元素是否满足条件

How to check if any of the elements satisfy a condition?

本文关键字:元素 是否 满足 条件 任何 何检查 检查      更新时间:2023-09-26

是否有任何方法来检查我的选择器中的任何元素是否满足特定条件?

目前我使用:

var isSatisfied = false;
$("#myUL li").each(function() {
    if($(this).data("myconditon") === true) {
        isSatisfied = true;
    }
});
// Use isSatisfied here

对于一个简单的工作来说,这似乎过于复杂了。我要找的是Enumerable之类的东西。

您可以使用。is(),但是您必须进行条件检查

var isSatisfied = $("#myUL li").is(function () {
    return $(this).data("myconditon") === true;
});
var isSatisfied = !!$("#myUL li").filter(function() {
    return $(this).data("myconditon") === true;
}).length;

.filter(),顾名思义,只保留回调返回true的那些项。所以我们最终得到了一个jQuery堆栈。通过查询它的长度,并将其强制转换为布尔值,您最终得到所需的布尔变量isSatisfied