如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
试试这个。
简单、简短,可在整个项目中使用:
jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin
用法:
console.log($("element-selector").exists());
_________________________________
或更短:(当您不想定义jQuery插件时):
if(!!$("elem-selector")[0]) ...;
甚至
if($("elem-selector")[0]) ...;
其他回答
您不必检查它是否大于0,例如$(selector).length>0,$(selected).llength,这就足够了,是检查元素存在的一种优雅方式。我认为仅为此编写函数是不值得的,如果你想做更多额外的事情,那么是的。
if($(selector).length){
// true if length is not 0
} else {
// false if length is 0
}
尝试测试DOM元素
if (!!$(selector)[0]) // do stuff
以下是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
}
);
实际上不需要jQuery。使用纯JavaScript,检查以下内容更容易且语义正确:
if(document.getElementById("myElement")) {
//Do something...
}
如果出于任何原因,您不想在元素中添加id,那么您仍然可以使用任何其他JavaScript方法来访问DOM。
jQuery确实很酷,但不要让纯JavaScript被遗忘。。。
如果输入不存在,它将没有值。试试这个。。。
if($(selector).val())