检查jQuery选择器是否找不到任何结果[重复]

时间:2022-09-22 16:55:39

This question already has an answer here:

这个问题在这里已有答案:

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()或nearest())

3 个解决方案

#1


32  

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

Used like:

使用如下:

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

#2


15  

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

使用长度是最好的方法。您不应该使用empty()或size()> 0,因为它只是向调用堆栈添加了另一个条目。

#3


11  

if ( $(selector)[0] )

That'll do it.

那就行了。

#1


32  

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

Used like:

使用如下:

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

#2


15  

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

使用长度是最好的方法。您不应该使用empty()或size()> 0,因为它只是向调用堆栈添加了另一个条目。

#3


11  

if ( $(selector)[0] )

That'll do it.

那就行了。