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

我现在的代码是:

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

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


当前回答

默认情况下-否。

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

if ($(selector).length)

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

其他回答

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

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

不需要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

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

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

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

一个用于id和类选择器的简单实用函数。

function exist(IdOrClassName, IsId) {
  var elementExit = false;
  if (IsId) {
    elementExit = $("#" + "" + IdOrClassName + "").length ? true : false;
  } else {
    elementExit = $("." + "" + IdOrClassName + "").length ? true : false;
  }
  return elementExit;
}

像下面这样调用此函数

$(document).ready(function() {
  $("#btnCheck").click(function() {
    //address is the id so IsId is true. if address is class then need to set IsId false
    if (exist("address", true)) {
      alert("exist");
    } else {
      alert("not exist");
    }
  });
});

您可以使用:

if ($(selector).is('*')) {
  // Do something
}

也许更优雅一点。