我怎么可以检查是否存在件在jQuery?

目前的代码,我已经是这样的:

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

是否有一个更优雅的方式来处理这个?也许是一个插件或功能?

有帮助吗?

解决方案

在JavaScript,一切都是真的'或'falsy',并对数字 0 (及南)的意思 false, ,其他的一切 true.所以你可以写:

if ($(selector).length)

你不需要那个 >0 部分。

其他提示

是的!

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 */ }

你也可以使用以下。如果没有值s目阵然后得到的第一个项目列将返回的定义。

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

你可以用这样的:

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

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

最快和最语义上的自我说明的方式检查存在,实际上是通过使用纯 JavaScript:

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

这是一个更长的时间才能写于延长替代方案,但执行速度更快,因为它是一个原JS方法。

这是更好地比替代的编写自己的 jQuery 功能。这种替代方法是速度较慢的原因,@snover说明。但它也给其他程序员的印象 exists() 功能是固有的东西来! JavaScript 会/应被理解通过其他编辑用你的代码时,没有增加知识的债务。

NB: 注意到缺乏一个'#'之前 element_id (因为这是纯JS,不 jQuery).

你可以省几个字节的文字:

if ($(selector)[0]) { ... }

这一工作,因为每个jQuery的对象还伪装成的一个阵列,使我们可以使用的阵列取消引用的操作者获得的第一个项目 阵列.它返回 undefined 如果没有项目指定的索引。

你可以使用:

if ($(selector).is('*')) {
  // 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

你可以指定一个或两个回调。第一个将火如果元素存在,第二个将火如果元素一样 存在。但是,如果你选择要通过唯一的一个功能,只会火时元存在。因此,链将会死亡,如果所选择的元素一样 存在。当然,如果它确实存在,第一功能将火和链将继续下去。

请记住,使用 回调变种有助于维持chainability –这件返回,并且你可以继续链式命令,如同任何其他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    */
    }
})

我看到大多数的答案都在这里 不准确的 因为他们应该是,他们检查件的长度,它可以 "确定" 在许多情况下,但不是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

有没有需要。真的。与普通JavaScript易和在语义上正确的检查:

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

如果由于任何原因你不想把一个id的元素,你仍然可以使用的任何其他JavaScript方法设计的访问DOM。

,这是真的很酷,但不要让纯JavaScript遗忘...

你可以用这个:

jQuery.fn.extend({
    exists: function() { return this.length }
});

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

原因以前所有的答案需要的 .length 参数是,他们大多使用google i/o大会的 $() 选择有querySelectorAll身后的窗帘(或者它们直接使用).这种方法是相当缓慢,因为它需要分析整个DOM树寻找 所有 比赛,选择和填充阵列。

该['length']的参数不需要或有用的代码,将会有很多更快,如果你直接使用 document.querySelector(selector) 相反,因为它返回的第一个元素相匹配或空,如果没有找到。

function elementIfExists(selector){  //named this way on purpose, see below
    return document.querySelector(selector);
}
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;

然而,这种方法使我们的实际目正在返回;它是好的,如果它不会被保存作为可变和反复使用(从而保持的参考,如果我们忘记).

var myel=elementIfExists("#myid");
// now we are using a reference to the element which will linger after removal
myel.getParentNode.removeChild(myel);
console.log(elementIfExists("#myid")); /* null */
console.log(myel); /* giant table lingering around detached from document */
myel=null; /* now it can be garbage collected */

在某些情况下这可能是需要的。它可以使用一个循环是这样的:

/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
    if (myel == myblacklistedel) break;

如果你实际上并不需要的元件,并希望得到/存储只是一个true/false,只要双不!它的工作鞋来不附带条件,那么,为什么结在这里?

function elementExists(selector){
    return !!document.querySelector(selector);
}
/* usage: */
var hastables = elementExists("table");  /* will be true or false */
if (hastables){
    /* insert css style sheet for our pretty tables */
}
setTimeOut(function (){if (hastables && !elementExists("#mytablecss"))
                           alert("bad table layouts");},3000);

我已经找到了 if ($(selector).length) {} 是不够的。它会悄悄地破坏你的应用程序时, selector 是一个空对象 {}.

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.');
}

我仍在寻找一个更好的解决方案,虽然作为一个沉重。

编辑: 警告! 这并不工作,在即的时候 selector 是一串。

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

$.contains() 你想要什么?

jQuery.contains( container, contained )

$.contains() 方法返回真的,如果DOM件提供的第二个论点是后代DOM件提供由第一个参数,它是否是直接的儿童或嵌套更深。否则,返回错误的。仅元节点是支持;如果第二个论点是一个文本或评论节点, $.contains() 将返回错误的。

注意到:第一个参数必须是一个DOM元素,不是一个jQuery对象或者纯JavaScript对象。

你可以检查件是存在或者不使用长在java脚本。如果长度大于零,那么元件是如果长为零然后 元素并不是本

// These by Id
if( $('#elementid').length > 0){
  // Element is Present
}else{
  // Element is not Present
}

// These by Class
if( $('.elementClass').length > 0){
  // Element is Present
}else{
  // Element is not Present
}

检查是否存在一个元素 记录整齐的在官方jQuery网站本身!

使用 .长 酒店的延收返回的你的 选择:

if ($("#myDiv").length) {
    $("#myDiv").show();
}

注意,它不是总是需要测试一个元件是否存在。以下代码显示的元素,如果它存在,什么也不做 (没有错误),如果它不:

$("#myDiv").show();

这是非常相似的所有答案,但是,为什么不用 ! 操作员的两倍,这样你就可以得到一个布尔:

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

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

尝试测试 DOM 元素

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

灵感 华威的答复 我想出了以下:

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

的!包含 需要两个DOM元素并检查是否是第一个包含的第二个。

使用 document.documentElement 作为第一个参数履行义的 exists 方法,当我们要应用它的全权检查存在的一个元素在目前的文件。

下面,我已经把一个片段比较 jQuery.exists() 反对 $(sel)[0]$(sel).length 方法这两者都返回 truthy$(4) 同时 $(4).exists() 返回 false.在该上下文中 检查存在 中一个元素DOM这似乎是的 预期的结果.

$.fn.exists = function() {
    return $.contains(document.documentElement, this[0]); 
  }
  
  var testFuncs = [
    function(jq) { return !!jq[0]; },
    function(jq) { return !!jq.length; },
    function(jq) { return jq.exists(); },
  ];
    
  var inputs = [
    ["$()",$()],
    ["$(4)",$(4)],
    ["$('#idoexist')",$('#idoexist')],
    ["$('#idontexist')",$('#idontexist')]
  ];
  
  for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {
    input = inputs[i][1];
    tr = "<tr><td>" + inputs[i][0] + "</td><td>"
          + testFuncs[0](input) + "</td><td>"
          + testFuncs[1](input) + "</td><td>"
          + testFuncs[2](input) + "</td></tr>";
    $("table").append(tr);
  }
td { border: 1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="idoexist">#idoexist</div>
<table style>
<tr>
  <td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>
</tr>
</table>
<script>
  
  $.fn.exists = function() {
    return $.contains(document.documentElement, this[0]); 
  }
  
</script>

我只是喜欢用普通javascript做到这一点。

function isExists(selector){
  return document.querySelectorAll(selector).length>0;
}

没有必要。

if(document.querySelector('.a-class')) {
  // 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");
});

它可能似乎很多代码,但是当写在抑很小:

$.fn.exists = (callback) ->
    exists = @length
    callback.call() if exists        
    new class
       otherwise: (fallback) ->            
            fallback.call() if not exists

我有一个情况下我想看看如果一个物体内存在的另一个使我增加点东西的第一个回答来检查一选择内部的选择..

// 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;
};

如何:

function exists(selector) {
    return $(selector).length;
}

if (exists(selector)) {
    // do something
}

这是很少有围的选择 $() 每一个时间。

我使用的是这个:

    $.fn.ifExists = function(fn) {
      if (this.length) {
        $(fn(this));
      }
    };
    $("#element").ifExists( 
      function($this){
        $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});               
      }
    ); 

执行链上,如果只有一个jQuery元素的存在- http://jsfiddle.net/andres_314/vbNM3/2/

这是我最喜欢的 exist 方法在jQuery

$.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
    }
);

$("selector")返回的一个目有 length 财产。如果选择现任何元素,它们将包括在对象。所以,如果你检查它的长你可以看到,如果任何元素存在。在JavaScript 0 == false, 所以如果你没得到 0 你的码将运行。

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

这里是完整示例的不同情况和方式,以检查,如果元素的存在使用直接的,如果在jQuery的选择可能会或可能不起作用,因为其返回阵或要素。

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

你不需要检查如果是大于 0 喜欢 $(selector).length > 0, $(selector).length 它的足够和优雅的方式来检查存在的因素。我不认为这是值得去写一个功能,只有为这个,如果你想要做更多的额外的东西,是的。

if($(selector).length){
  // true if length is not 0
} else {
  // false if length is 0
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top