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

我现在的代码是:

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

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


当前回答

该插件可以在if语句中使用,如if($(ele).exist()){/*DO WORK*/}或使用回调。

插件

;;(function($) {
    if (!$.exist) {
        $.extend({
            exist: function() {
                var ele, cbmExist, cbmNotExist;
                if (arguments.length) {
                    for (x in arguments) {
                        switch (typeof arguments[x]) {
                            case 'function':
                                if (typeof cbmExist == "undefined") cbmExist = arguments[x];
                                else cbmNotExist = arguments[x];
                                break;
                            case 'object':
                                if (arguments[x] instanceof jQuery) ele = arguments[x];
                                else {
                                    var obj = arguments[x];
                                    for (y in obj) {
                                        if (typeof obj[y] == 'function') {
                                            if (typeof cbmExist == "undefined") cbmExist = obj[y];
                                            else cbmNotExist = obj[y];
                                        }
                                        if (typeof obj[y] == 'object' && obj[y] instanceof jQuery) ele = obj[y];
                                        if (typeof obj[y] == 'string') ele = $(obj[y]);
                                    }
                                }
                                break;
                            case 'string':
                                ele = $(arguments[x]);
                                break;
                        }
                    }
                }

                if (typeof cbmExist == 'function') {
                    var exist =  ele.length > 0 ? true : false;
                    if (exist) {
                        return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });
                    }
                    else if (typeof cbmNotExist == 'function') {
                        cbmNotExist.apply(ele, [exist, ele]);
                        return ele;
                    }
                    else {
                        if (ele.length <= 1) return ele.length > 0 ? true : false;
                        else return ele.length;
                    }
                }
                else {
                    if (ele.length <= 1) return ele.length > 0 ? true : false;
                    else return ele.length;
                }

                return false;
            }
        });
        $.fn.extend({
            exist: function() {
                var args = [$(this)];
                if (arguments.length) for (x in arguments) args.push(arguments[x]);
                return $.exist.apply($, args);
            }
        });
    }
})(jQuery);

jsFiddle公司

您可以指定一个或两个回调。如果元素存在,第一个将激发,如果元素不存在,第二个将激发。但是,如果您选择只传递一个函数,那么它只会在元素存在时激发。因此,如果所选元素不存在,则链将死亡。当然,如果它确实存在,第一个函数将启动,链将继续。

请记住,使用回调变量有助于保持可链接性——元素被返回,您可以像使用任何其他jQuery方法一样继续链接命令!

示例用途

if ($.exist('#eleID')) {    /*    DO WORK    */ }        //    param as STRING
if ($.exist($('#eleID'))) { /*    DO WORK    */ }        //    param as jQuery OBJECT
if ($('#eleID').exist()) {  /*    DO WORK    */ }        //    enduced on jQuery OBJECT

$.exist('#eleID', function() {            //    param is STRING && CALLBACK METHOD
    /*    DO WORK    */
    /*    This will ONLY fire if the element EXIST    */
}, function() {            //    param is STRING && CALLBACK METHOD
    /*    DO WORK    */
    /*    This will ONLY fire if the element DOES NOT EXIST    */
})

$('#eleID').exist(function() {            //    enduced on jQuery OBJECT with CALLBACK METHOD
    /*    DO WORK    */
    /*    This will ONLY fire if the element EXIST    */
})

$.exist({                        //    param is OBJECT containing 2 key|value pairs: element = STRING, callback = METHOD
    element: '#eleID',
    callback: function() {
        /*    DO WORK    */
        /*    This will ONLY fire if the element EXIST    */
    }
})

其他回答

if ( $('#myDiv').size() > 0 ) { //do something }

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

有一种奇怪的现象叫做短路调节。没有多少人知道这个功能,所以请允许我解释一下<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相同的性能,并且被认为有点简洁。测试条件的性能和逻辑运算符的使用。

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

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

您可以使用此选项:

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

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

是的最佳方法:

通过JQuery:

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

选择器可以是元素ID或元素类

OR

如果您不想使用jQuery Library,那么可以通过使用Core JavaScript实现这一点:

通过JavaScript:

if(document.getElementById("ElementID")) {
    //Do something...
}

我使用的是:

 if($("#element").length > 0){
   //the element exists in the page, you can do the rest....
 }

它非常简单,很容易找到元素。