如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
您可以在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
}
其他回答
在JavaScript中,一切都是“truthy”或“falsy”,对于数字0表示假,其他一切都是真。所以你可以写:
if ($(selector).length)
你不需要那>0部分。
Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
这是对杰夫·阿特伍德主持的《放牧守则》播客的回应
这里是不同情况的完整示例,以及使用jQuery选择器上的direct-if检查元素是否存在的方法,因为它返回数组或元素,所以它可能工作,也可能不工作。
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
Demo
console.log(“现有id”,$('#id-1').length)console.log(“非现有id”,$('#id-2').length)console.log(“现有类单个实例”,$('.cls-1').length)console.log(“现有类多实例”,$('.cls-2').length)console.log(“非现有类”,$('.cls-3').length)<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“id-1”><div class=“cls-1cls-2”></div><div class=“cls-2”></div></div>
您可以通过以下方式节省几个字节:
if ($(selector)[0]) { ... }
这是因为每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用运算符从数组中获取第一个项。如果指定索引中没有项,则返回undefined。
一个用于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");
}
});
});