如何检查jQuery中元素的存在?

我现在的代码是:

if ($(selector).length > 0) {
    // Do something
}

有没有更优雅的方式来处理这个问题?也许是插件或函数?


当前回答

您可以通过以下方式节省几个字节:

if ($(selector)[0]) { ... }

这是因为每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用运算符从数组中获取第一个项。如果指定索引中没有项,则返回undefined。

其他回答

怎么样:

function exists(selector) {
    return $(selector).length;
}

if (exists(selector)) {
    // do something
}

它非常简单,而且每次都不用用$()括住选择器。

$(“selector”)返回一个具有长度属性的对象。如果选择器找到任何元素,它们将包含在对象中。所以如果你检查它的长度,你可以看到是否有元素存在。在JavaScript中,0==false,因此如果没有得到0,代码将运行。

if($("selector").length){
   //code in the case
} 

如果输入不存在,它将没有值。试试这个。。。

if($(selector).val())

只需检查选择器的长度,如果它大于0,则返回true,否则返回false。

对于ID:

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}

对于类别:

 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

对于下拉列表:

if( $('#selector option').size() ) {   // use this if you are using dropdown size to check

   // it exists
}

您可以通过以下方式节省几个字节:

if ($(selector)[0]) { ... }

这是因为每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用运算符从数组中获取第一个项。如果指定索引中没有项,则返回undefined。