Javascript 是否有一个「;“存在”;jQuery的函数?

Javascript 是否有一个「;“存在”;jQuery的函数?,javascript,jquery,Javascript,Jquery,如何检查jQuery中元素的存在性 我目前拥有的代码如下: if ($(selector).length > 0) { // Do something } 有没有更优雅的方法?也许是一个插件或一个函数?是的 jQuery.fn.exists = function(){ return this.length > 0; } if ($(selector).exists()) { // Do something } 这是对以下内容的响应:您可以使用: if ($(se

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

我目前拥有的代码如下:

if ($(selector).length > 0) {
    // Do something
}
有没有更优雅的方法?也许是一个插件或一个函数?

是的

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

if ($(selector).exists()) {
    // Do something
}
这是对以下内容的响应:

您可以使用:

if ($(selector).is('*')) {
  // Do something
}
一点可能更优雅。

如果你用

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
你可能会暗示链接是可能的,但事实并非如此

这样会更好:

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

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

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

在JavaScript中,所有内容都是“truthy”或“falsy”,对于数字
0
意味着
false
,其他所有内容
true
。所以你可以写:

if ($(selector).length)
您不需要该
>0
部件。

您可以使用该部件:

// if element exists
if($('selector').length){ /* do something */ }
jQuery.fn.extend({
    exists: function() { return this.length }
});

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


实际上没有必要使用jQuery。使用纯JavaScript,检查以下内容更容易且语义正确:

if(document.getElementById("myElement")) {
    //Do something...
}
如果出于任何原因您不想为元素添加id,您仍然可以使用任何其他设计用于访问DOM的JavaScript方法


jQuery确实很酷,但不要让纯JavaScript被遗忘…

检查存在性的最快、最语义自我解释的方法实际上是使用普通的
JavaScript

if (document.getElementById('element_id')) {
    // Do something
}
与jQuery-length替代方法相比,它的写入时间稍长,但执行速度更快,因为它是本机JS方法

它比编写自己的
jQuery
函数要好。出于@snover所述的原因,这种选择的速度较慢。但它也会给其他程序员一种印象,即
exists()
函数是jQuery固有的功能<代码>JavaScript将/应该被编辑您代码的其他人理解,而不会增加知识债务

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

我发现
if($(选择器).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.');
}
我唯一的建议是对
{}
执行额外的检查

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

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

// 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;
};
我用这个:

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

仅当jQuery元素存在时才执行链-

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

插件 你可以用这个:

// if element exists
if($('selector').length){ /* do something */ }
jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something*/}
这是你想要的吗

jQuery.contains(容器,contained)

如果第二个参数提供的DOM元素是第一个参数提供的DOM元素的后代,则
$.contains()
方法返回true,无论它是直接子元素还是嵌套得更深。否则,它将返回false。仅支持元素节点;如果第二个参数是文本或注释节点,
$.contains()
将返回false

注意:第一个参数必须是DOM元素,而不是jQuery对象或普通JavaScript对象


您可以通过写入以下内容来节省几个字节:

if ($(selector)[0]) { ... }
这是因为每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用操作符从数组中获取第一项。如果指定索引中没有项,则返回未定义的。

如何:

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

if (exists(selector)) {
    // 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");
});
它可能看起来有很多代码,但当用CoffeeScript编写时,它相当小:

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

前面的所有答案都需要
.length
参数的原因是,它们主要使用jquery的
$()
选择器,该选择器在窗帘后面有querySelectorAll(或者它们直接使用它)。这个方法相当慢,因为它需要解析整个DOM树,查找与该选择器的所有匹配项,并用它们填充数组

如果直接使用
document.querySelector(selector)
,则['length']参数不是必需的或有用的,而且代码速度会快得多,因为它返回匹配的第一个元素,如果找不到,则返回null

function elementIfExists(selector){  //named this way on purpose, see below
    return document.querySelector(selector);
}
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;
然而,这个方法留给我们的是返回的实际对象;如果不将其保存为变量并重复使用(这样,如果我们忘记了,就可以保留引用),这是很好的

在某些情况下,这可能是需要的。它可以在如下的for循环中使用:

/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
    if (myel == myblacklistedel) break;
如果您实际上不需要该元素,并且只想获得/存储一个真/假,只需加倍,而不是加倍!!它适用于解开的鞋子,为什么在这里打结

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);

这与所有答案非常相似,但为什么不使用
运算符两次,以便获得布尔值:

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

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

您可以在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
}

尝试测试
DOM
元素

if (!!$(selector)[0]) // do stuff
受此启发,我提出了以下建议:

$.fn.exists = function() {
    return $.contains( document.documentElement, this[0] );
}
获取两个DOM元素并检查第一个元素是否包含第二个元素

使用
document.documentElement
作为第一个参数满足了
exists
方法的语义,我们只想将其应用于检查当前文档中是否存在元素

下面,我整理了一个比较
jQuery.exis的代码片段
if (!!$(selector)[0]) // do stuff
$.fn.exists = function() {
    return $.contains( document.documentElement, this[0] );
}
$.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($("selector").length){
   //code in the case
} 
function isExists(selector){
  return document.querySelectorAll(selector).length>0;
}
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
if(document.querySelector('.a-class')) {
  // do something
}
if(document.getElementsByClassName('a-class')[0]) {
  // do something
}
if ($("#myDiv").length) {
    $("#myDiv").show();
}
$("#myDiv").show();
$.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
if($(selector).length){
  // true if length is not 0
} else {
  // false if length is 0
}