如何检查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

其他回答

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

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

有一种奇怪的现象叫做短路调节。没有多少人知道这个功能,所以请允许我解释一下<3.

//you can check if it isnt defined or if its falsy by using OR
console.log( $(selector) || 'this value doesnt exist' )

//or run the selector if its true, and ONLY true
console.log( $(selector) && 'this selector is defined, now lemme do somethin!' )

//sometimes I do the following, and see how similar it is to SWITCH
console.log(
({  //return something only if its in the method name
    'string':'THIS is a string',
    'function':'THIS is a function',
    'number':'THIS is a number',
    'boolean':'THIS is a boolean'
})[typeof $(selector)]||
//skips to this value if object above is undefined
'typeof THIS is not defined in your search')

最后一位允许我查看我的类型有什么样的输入,并在列表中运行。如果列表中有一个值,我使用OR(||)运算符跳过并使其无效。这具有与Switch Case相同的性能,并且被认为有点简洁。测试条件的性能和逻辑运算符的使用。

附带说明:对象函数需要重写>.<'但我所做的这个测试是为了研究简洁而富有表现力的条件反射。

资源:逻辑与(带短路评估)

这与所有答案非常相似,但为什么不使用!运算符两次,这样可以得到布尔值:

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

if ($(selector).exists()) {
    // the element exists, now what?...
}

在JavaScript中,一切都是“truthy”或“falsy”,对于数字0表示假,其他一切都是真。所以你可以写:

if ($(selector).length)

你不需要那>0部分。

尝试测试DOM元素

if (!!$(selector)[0]) // do stuff