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

我现在的代码是:

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

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


当前回答

我偶然发现了这个问题,我想分享一段我目前使用的代码:

$.fn.exists = function(callback) {
    var self = this;
    var wrapper = (function(){
            function notExists () {}

            notExists.prototype.otherwise = function(fallback){
                if (!self.length) {                    
                    fallback.call();
                }
            };

            return new notExists;
        })();

    if(self.length) {
        callback.call();    
    }

    return wrapper;
}

现在我可以编写这样的代码了-

$("#elem").exists(function(){
    alert ("it exists");
}).otherwise(function(){
    alert ("it doesn't exist");
});

它可能看起来有很多代码,但当用CoffeeScript编写时,它非常小:

$.fn.exists = (callback) ->
    exists = @length
    callback.call() if exists        
    new class
       otherwise: (fallback) ->            
            fallback.call() if not exists

其他回答

您不必检查它是否大于0,例如$(selector).length>0,$(selected).llength,这就足够了,是检查元素存在的一种优雅方式。我认为仅为此编写函数是不值得的,如果你想做更多额外的事情,那么是的。

if($(selector).length){
  // true if length is not 0
} else {
  // false if length is 0
}
if ( $('#myDiv').size() > 0 ) { //do something }

size()统计选择器返回的元素数

默认情况下-否。

长度属性通常以以下方式用于相同的结果:

if ($(selector).length)

在这里,“选择器”将被您感兴趣的实际选择器替换,无论它是否存在。如果它确实存在,那么length属性将输出一个大于0的整数,因此If语句将变为true,从而执行If块。如果没有,它将输出整数“0”,因此If块不会被执行。

将querySelectorAll与forEach一起使用,无需if和额外赋值:

document.querySelectorAll('.my-element').forEach((element) => {
  element.classList.add('new-class');
});

与以下内容相反:

const myElement = document.querySelector('.my-element');
if (myElement) {
  element.classList.add('new-class');
}

您可以使用此选项:

// if element exists
if($('selector').length){ /* do something */ }

// if element does not exist
if(!$('selector').length){ /* do something */ }