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

我现在的代码是:

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

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


当前回答

在JavaScript中,一切都是“truthy”或“falsy”,对于数字0表示假,其他一切都是真。所以你可以写:

if ($(selector).length)

你不需要那>0部分。

其他回答

Yes!

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

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

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

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

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

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

有一种奇怪的现象叫做短路调节。没有多少人知道这个功能,所以请允许我解释一下<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($(“#myDiv”).length){$(“#myDiv”).show();}注意,并不总是需要测试元素是否存在。下面的代码将显示元素(如果存在),并且不做任何操作(无错误)如果没有:$(“#myDiv”).show();

感谢您分享这个问题。首先,有多种方法可以检查它。如果您想检查DOM中是否存在HTML元素。为此,您可以尝试以下方法。

使用Id选择器:在DOM中按Id选择元素,应该提供以前缀(#)开头的Id名称。您必须确保DOM中的每个Html元素都必须具有唯一的id。使用类选择器:可以使用前缀(.)选择属于特定类的所有元素。

现在,如果您想检查元素是否存在于DOM中,可以使用以下代码检查它。

if($(“#myId”).length){//id选择器} if($(“.myClass”).length){//类别选择器}

如果要检查任何变量是否未定义。您可以使用以下代码进行检查。

让x如果(x)console.log(“X”);其他的console.log(“X未定义”);