检查 jQuery 选择器是否找不到任何结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7141334/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:27:38  来源:igfitidea点击:

Checking if a jQuery selector doesn't find any results

jquery

提问by micho

I'm used to Prototypejs, where $$("selector") will return null if no elements were found. This is convenient because I can do

我习惯了 Prototypejs,如果没有找到元素,$$("selector") 将返回 null。这很方便,因为我可以做到

if ($$("selector")) {}

to check if an element is in the DOM.

检查元素是否在 DOM 中。

However, in jQuery $(selector) will return [] if no element is found, so now I need to do:

但是,在 jQuery 中 $(selector) 将返回 [] 如果没有找到元素,所以现在我需要做:

if ( $(selector).length > 0 )

This makes code slightly harder to read.

这使得代码更难阅读。

My question: What's the best way of doing this? Should I extend the jQuery object with methods like .empty() and .any(), or are there built in functions to do this?

我的问题:这样做的最佳方法是什么?我应该使用 .empty() 和 .any() 等方法扩展 jQuery 对象,还是有内置函数来执行此操作?

Update: This also applies to other selectors on jQuery which should, anyways, only return one result (like parent(), or closest())

更新:这也适用于 jQuery 上的其他选择器,无论如何,它们应该只返回一个结果(如 parent() 或最接近的 ())

采纳答案by Baz1nga

$.fn.exists = function () {
    return this.length !== 0;
}

Used like:

像这样使用:

$("#notAnElement").exists();

回答by Chris Laplante

Using lengthis the best way. You shouldn't use empty()or size() > 0since that just adds another entry to the call stack.

使用length是最好的方法。您不应该使用empty()orsize() > 0因为它只是在调用堆栈中添加了另一个条目。

回答by Joseph Marikle

if ( $(selector)[0] )

That'll do it.

这样就可以了。