如何检查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
}
其他回答
怎么样:
function exists(selector) {
return $(selector).length;
}
if (exists(selector)) {
// do something
}
它非常简单,而且每次都不用用$()括住选择器。
这与所有答案非常相似,但为什么不使用!运算符两次,这样可以得到布尔值:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
您可以通过以下方式节省几个字节:
if ($(selector)[0]) { ... }
这是因为每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用运算符从数组中获取第一个项。如果指定索引中没有项,则返回undefined。
以下是jQuery中我最喜欢的exist方法
$.fn.exist = function(callback) {
return $(this).each(function () {
var target = $(this);
if (this.length > 0 && typeof callback === 'function') {
callback.call(target);
}
});
};
以及在选择器不存在时支持回调的其他版本
$.fn.exist = function(onExist, onNotExist) {
return $(this).each(function() {
var target = $(this);
if (this.length > 0) {
if (typeof onExist === 'function') {
onExist.call(target);
}
} else {
if (typeof onNotExist === 'function') {
onNotExist.call(target);
}
}
});
};
例子:
$('#foo .bar').exist(
function () {
// Stuff when '#foo .bar' exists
},
function () {
// Stuff when '#foo .bar' does not exist
}
);
受到海威回答的启发,我想到了以下几点:
$.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>