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

我现在的代码是:

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

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


当前回答

检查是否存在的最快和最语义自解释的方法实际上是使用普通JavaScript:

if (document.getElementById('element_id')) {
    // Do something
}

它比jQuery长度替代方案要长一点,但执行速度更快,因为它是一个原生JS方法。

它比编写自己的jQuery函数要好。出于snover所说的原因,这种替代方案要慢一些。但这也会给其他程序员留下这样的印象:exists()函数是jQuery固有的东西。JavaScript会/应该被其他编辑代码的人理解,而不会增加知识债务。

注意:注意element_id前面缺少“#”(因为这是纯JS,而不是jQuery)。

其他回答

如果您使用

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }

你会暗示链接是可能的,而不是可能的。

这样会更好:

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }

或者,从常见问题解答:

if ( $('#myDiv').length ) { /* Do something */ }

您也可以使用以下选项。如果jQuery对象数组中没有值,那么获取数组中的第一个项将返回undefined。

if ( $('#myDiv')[0] ) { /* Do something */ }

怎么样:

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

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

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

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

if($(selector).val())

以下是jQuery中我最喜欢的exist方法

$.fn.exist = function(callback) {
    return $(this).each(function () {
        var target = $(this);

        if (this.length > 0 && typeof callback === 'function') {
            callback.call(target);
        }
    });
};

以及在选择器不存在时支持回调的其他版本

$.fn.exist = function(onExist, onNotExist) {
    return $(this).each(function() {
        var target = $(this);

        if (this.length > 0) {
            if (typeof onExist === 'function') {
                onExist.call(target);
            }
        } else {
            if (typeof onNotExist === 'function') {
                onNotExist.call(target);
            }
        }
    });
};

例子:

$('#foo .bar').exist(
    function () {
        // Stuff when '#foo .bar' exists
    },
    function () {
        // Stuff when '#foo .bar' does not exist
    }
);

我只是喜欢使用普通的javascript来实现这一点。

function isExists(selector){
  return document.querySelectorAll(selector).length>0;
}