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