如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
在Javascript中
if (typeof selector != "undefined") {
console.log("selector exists");
} else {
console.log("selector does not exists");
}
在jQuery中
if($('selector').length){
alert("selector exists");
} else{
alert("selector does not exists");
}
其他回答
检查是否存在的最快和最语义自解释的方法实际上是使用普通JavaScript:
if (document.getElementById('element_id')) {
// Do something
}
它比jQuery长度替代方案要长一点,但执行速度更快,因为它是一个原生JS方法。
它比编写自己的jQuery函数要好。出于snover所说的原因,这种替代方案要慢一些。但这也会给其他程序员留下这样的印象:exists()函数是jQuery固有的东西。JavaScript会/应该被其他编辑代码的人理解,而不会增加知识债务。
注意:注意element_id前面缺少“#”(因为这是纯JS,而不是jQuery)。
这里是不同情况的完整示例,以及使用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 ( $('#myDiv').size() > 0 ) { //do something }
size()统计选择器返回的元素数
我正在使用这个:
$.fn.ifExists = function(fn) {
if (this.length) {
$(fn(this));
}
};
$("#element").ifExists(
function($this){
$this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});
}
);
仅当jQuery元素存在时执行链-http://jsfiddle.net/andres_314/vbNM3/2/
您可以通过以下方式节省几个字节:
if ($(selector)[0]) { ... }
这是因为每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用运算符从数组中获取第一个项。如果指定索引中没有项,则返回undefined。