如何检查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");
}
其他回答
我发现这是最jQuery的方式,IMHO。扩展默认函数很简单,可以在全局扩展文件中完成。
$.fn.exist=函数(){回来此长度;};console.log($(“#yes”).exist())console.log($(“#no”).exist())<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“yes”>id=是</div>
实际上不需要jQuery。使用纯JavaScript,检查以下内容更容易且语义正确:
if(document.getElementById("myElement")) {
//Do something...
}
如果出于任何原因,您不想在元素中添加id,那么您仍然可以使用任何其他JavaScript方法来访问DOM。
jQuery确实很酷,但不要让纯JavaScript被遗忘。。。
我只是喜欢使用普通的javascript来实现这一点。
function isExists(selector){
return document.querySelectorAll(selector).length>0;
}
受到海威回答的启发,我想到了以下几点:
$.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中我最喜欢的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
}
);