如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
我发现if($(selector).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.');
}
我仍然在寻找一个更好的解决方案,尽管这个有点重。
编辑:警告!当选择器是字符串时,这在IE中不起作用。
$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
其他回答
只需检查选择器的长度,如果它大于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
}
感谢您分享这个问题。首先,有多种方法可以检查它。如果您想检查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未定义”);
不,没有这样的方法。但是您可以为自己的jQuery扩展jQuery。目前(2022年)的做法是:
jQuery.fn.extend({
exists() { return !!this.length }
});
我发现if($(selector).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.');
}
我仍然在寻找一个更好的解决方案,尽管这个有点重。
编辑:警告!当选择器是字符串时,这在IE中不起作用。
$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
您可以通过以下方式节省几个字节:
if ($(selector)[0]) { ... }
这是因为每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用运算符从数组中获取第一个项。如果指定索引中没有项,则返回undefined。