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

我现在的代码是:

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

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


当前回答

默认情况下-否。

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

if ($(selector).length)

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

其他回答

该插件可以在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($(selector).length){}不够。当选择器为空对象{}时,它将自动中断应用程序。

var $target = $({});        
console.log($target, $target.length);

// Console output:
// -------------------------------------
// [▼ Object              ] 1
//    ► __proto__: Object

我唯一的建议是对{}执行额外的检查。

if ($.isEmptyObject(selector) || !$(selector).length) {
    throw new Error('Unable to work with the given selector.');
}

我仍然在寻找一个更好的解决方案,尽管这个有点重。

编辑:警告!当选择器是字符串时,这在IE中不起作用。

$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE

不需要jQuery(基本解决方案)

if(document.querySelector('.a-class')) {
  // do something
}

下面的选项性能更高(注意a类前面没有点)。

if(document.getElementsByClassName('a-class')[0]) {
  // do something
}

querySelector在jQuery中使用了一个适当的匹配引擎,比如$()(sizzle),并使用了更多的计算能力,但在99%的情况下都会很好。第二个选项更加明确,并且告诉代码要做什么https://jsbench.me/65l2up3t8i

这里是不同情况的完整示例,以及使用jQuery选择器上的direct-if检查元素是否存在的方法,因为它返回数组或元素,所以它可能工作,也可能不工作。

var a = null;

var b = []

var c = undefined ;

if(a) { console.log(" a exist")} else { console.log("a doesn't exit")}
// output: a doesn't exit

if(b) { console.log(" b exist")} else { console.log("b doesn't exit")}
// output: b exist

if(c) { console.log(" c exist")} else { console.log("c doesn't exit")}
// output: c doesn't exit

最终解决方案

if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist

if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
    //output : xusyxxs doesnn't exist

Demo

console.log(“现有id”,$('#id-1').length)console.log(“非现有id”,$('#id-2').length)console.log(“现有类单个实例”,$('.cls-1').length)console.log(“现有类多实例”,$('.cls-2').length)console.log(“非现有类”,$('.cls-3').length)<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“id-1”><div class=“cls-1cls-2”></div><div class=“cls-2”></div></div>

检查元素的存在在jQuery官方网站中有完整的文档记录!

使用选择器:if($(“#myDiv”).length){$(“#myDiv”).show();}注意,并不总是需要测试元素是否存在。下面的代码将显示元素(如果存在),并且不做任何操作(无错误)如果没有:$(“#myDiv”).show();