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

我现在的代码是:

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

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


当前回答

我发现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

其他回答

该插件可以在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    */
    }
})

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

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

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

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

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

我发现这是最jQuery的方式,IMHO。扩展默认函数很简单,可以在全局扩展文件中完成。

$.fn.exist=函数(){回来此长度;};console.log($(“#yes”).exist())console.log($(“#no”).exist())<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“yes”>id=是</div>

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

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

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

我有一个例子,我想看看一个对象是否存在于另一个对象中,所以我在第一个答案中添加了一些东西,以检查选择器中的选择器。。

// Checks if an object exists.
// Usage:
//
//     $(selector).exists()
//
// Or:
// 
//     $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
    return selector ? this.find(selector).length : this.length;
};