如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
只需检查选择器的长度,如果它大于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
}
其他回答
受到海威回答的启发,我想到了以下几点:
$.fn.exists = function() {
return $.contains( document.documentElement, this[0] );
}
jQuery.contains获取两个DOM元素,并检查第一个元素是否包含第二个元素。
当我们希望仅应用document.documentElement来检查当前文档中元素的存在时,使用document.documentsElement作为第一个参数可以实现exists方法的语义。
下面,我将jQuery.exists()与$(sel)[0]和$(sel).length方法进行了比较,这两种方法都返回了$(4)的真值,而$(4().exists)返回了假值。在检查DOM中是否存在元素的上下文中,这似乎是理想的结果。
$.fn.exists=函数(){return$.contains(document.documentElement,this[0]);}var测试功能=[函数(jq){return!!jq[0];},函数(jq){return!!jq.length;},函数(jq){return jq.exists();},];var输入=[["$()",$()],["$(4)",$(4)],[“$('#idexist')”,$('#idexist])],[“$('#idotexist')”,$('#idotexit')]];for(变量i=0,l=inputs.length,tr,input;i<l;i++){input=输入[i][1];tr=“<tr><td>”+输入[i][0]+“</td><td]”+testFuncs[0](输入)+“</td><td>”+testFuncs[1](输入)+“</td><td>”+testFuncs[2](输入)+“</td></tr>”;$(“table”).append(tr);}td{border:1px实心黑色}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div id=“idexist”>#idexist</div><表格样式><tr><td>输入</td><td>$(sel)[0]</td><td>$(sel).length</td><td>$(sel).exists()</td></tr></table><脚本>$.fn.exists=函数(){return$.contains(document.documentElement,this[0]);}</script>
这与所有答案非常相似,但为什么不使用!运算符两次,这样可以得到布尔值:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
您不必检查它是否大于0,例如$(selector).length>0,$(selected).llength,这就足够了,是检查元素存在的一种优雅方式。我认为仅为此编写函数是不值得的,如果你想做更多额外的事情,那么是的。
if($(selector).length){
// true if length is not 0
} else {
// false if length is 0
}
试试这个。
简单、简短,可在整个项目中使用:
jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin
用法:
console.log($("element-selector").exists());
_________________________________
或更短:(当您不想定义jQuery插件时):
if(!!$("elem-selector")[0]) ...;
甚至
if($("elem-selector")[0]) ...;
检查jQuery中是否存在元素并不是所有的答案都是无懈可击的。经过多年的编码,只有此解决方案不会对存在与否发出任何警告:
if($(selector).get(0)) { // Do stuff }
或者在你的职能开始时保释:
if(!$(selector).get(0)) return;
解释
在这种情况下,您不必处理零|空长度问题。这会强制获取一个元素,而不是计算它们。