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

我现在的代码是:

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

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


当前回答

Yes!

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

if ($(selector).exists()) {
    // Do something
}

这是对杰夫·阿特伍德主持的《放牧守则》播客的回应

其他回答

如果您使用

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }

你会暗示链接是可能的,而不是可能的。

这样会更好:

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }

或者,从常见问题解答:

if ( $('#myDiv').length ) { /* Do something */ }

您也可以使用以下选项。如果jQuery对象数组中没有值,那么获取数组中的第一个项将返回undefined。

if ( $('#myDiv')[0] ) { /* Do something */ }

以下是jQuery中我最喜欢的exist方法

$.fn.exist = function(callback) {
    return $(this).each(function () {
        var target = $(this);

        if (this.length > 0 && typeof callback === 'function') {
            callback.call(target);
        }
    });
};

以及在选择器不存在时支持回调的其他版本

$.fn.exist = function(onExist, onNotExist) {
    return $(this).each(function() {
        var target = $(this);

        if (this.length > 0) {
            if (typeof onExist === 'function') {
                onExist.call(target);
            }
        } else {
            if (typeof onNotExist === 'function') {
                onNotExist.call(target);
            }
        }
    });
};

例子:

$('#foo .bar').exist(
    function () {
        // Stuff when '#foo .bar' exists
    },
    function () {
        // Stuff when '#foo .bar' does not exist
    }
);
if ( $('#myDiv').size() > 0 ) { //do something }

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

我看到这里的大多数答案都不准确,他们检查了元素长度,在很多情况下都可以,但不是100%,想象一下如果数字传递给函数,所以我原型化了一个函数,它检查所有条件并返回应该的答案:

$.fn.exists = $.fn.exists || function() { 
  return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement)); 
}

这将检查长度和类型,现在您可以这样检查:

$(1980).exists(); //return false
$([1,2,3]).exists(); //return false
$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
$([{nodeName: 'foo'}]).exists() // returns false
$('div').exists(); //return true
$('.header').exists(); //return true
$(document).exists(); //return true
$('body').exists(); //return true

受到海威回答的启发,我想到了以下几点:

$.fn.exists = function() {
    return $.contains( document.documentElement, this[0] );
}

jQuery.contains获取两个DOM元素,并检查第一个元素是否包含第二个元素。

当我们希望仅应用document.documentElement来检查当前文档中元素的存在时,使用document.documentsElement作为第一个参数可以实现exists方法的语义。

下面,我将jQuery.exists()与$(sel)[0]和$(sel).length方法进行了比较,这两种方法都返回了$(4)的真值,而$(4().exists)返回了假值。在检查DOM中是否存在元素的上下文中,这似乎是理想的结果。

$.fn.exists=函数(){return$.contains(document.documentElement,this[0]);}var测试功能=[函数(jq){return!!jq[0];},函数(jq){return!!jq.length;},函数(jq){return jq.exists();},];var输入=[["$()",$()],["$(4)",$(4)],[“$('#idexist')”,$('#idexist])],[“$('#idotexist')”,$('#idotexit')]];for(变量i=0,l=inputs.length,tr,input;i<l;i++){input=输入[i][1];tr=“<tr><td>”+输入[i][0]+“</td><td]”+testFuncs[0](输入)+“</td><td>”+testFuncs[1](输入)+“</td><td>”+testFuncs[2](输入)+“</td></tr>”;$(“table”).append(tr);}td{border:1px实心黑色}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div id=“idexist”>#idexist</div><表格样式><tr><td>输入</td><td>$(sel)[0]</td><td>$(sel).length</td><td>$(sel).exists()</td></tr></table><脚本>$.fn.exists=函数(){return$.contains(document.documentElement,this[0]);}</script>