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

我现在的代码是:

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

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


当前回答

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

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

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

其他回答

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

默认情况下-否。

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

if ($(selector).length)

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

如果输入不存在,它将没有值。试试这个。。。

if($(selector).val())

检查元素的存在在jQuery官方网站中有完整的文档记录!

使用选择器:if($(“#myDiv”).length){$(“#myDiv”).show();}注意,并不总是需要测试元素是否存在。下面的代码将显示元素(如果存在),并且不做任何操作(无错误)如果没有:$(“#myDiv”).show();

只需检查选择器的长度,如果它大于0,则返回true,否则返回false。

对于ID:

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}

对于类别:

 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

对于下拉列表:

if( $('#selector option').size() ) {   // use this if you are using dropdown size to check

   // it exists
}