检查 jQuery 对象是否有任何匹配元素的最快方法
假设我有一个巨大的树视图,其中一个分支位于名为 $branch
的变量中,现在我想检查该分支是否包含无或多个元素 与扩展 类。换句话说,一旦找到匹配项就应该返回布尔值。
好的,我可以用 $branch.find('.expand').length > 来做到这一点0
,但是有没有更好的方法可以在第一个匹配元素上停止,从而更快?
我认为使用 first()
将现有集合的长度减少为 1,所以我会使用 find()
然后减少?
诗。正如您在示例中注意到的那样,我使用了 find()
,因为我想要更深入地了解 $branch
的子级。
Let's say I have huge tree view and one the branches is in variable called $branch
and now I want to check does that branch contain none or more than one element with expand classes. In other words boolean should be returned as soon as one match is found.
Okay, I can do this with $branch.find('.expand').length > 0
, but is there a better way that would stop on the first matching element and therefore would be faster?
I think using first()
reduces existing set to length of one, so I would have use find()
and then reduce?
Ps. As you noticed in the example I used find()
because I want to go deeper than just children of the $branch
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的标准 CSS 选择器使用本机 DOM 方法 querySelectorAll()。即它们在浏览器的本机代码中运行并且速度很快。除非您有理由认为执行上述操作很慢,否则我怀疑您不需要担心它。
Standard CSS selectors like this use the native DOM method querySelectorAll(). I.e. they run in the browser's native code and they're fast. Unless you've got reason to think that doing the above is slow, I doubt you need to worry about it.
您肯定想看看
.has()
方法。You definitely want to take a look at the
.has()
method.