如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
您可以使用:
if ($(selector).is('*')) {
// Do something
}
也许更优雅一点。
其他回答
您可以使用:
if ($(selector).is('*')) {
// Do something
}
也许更优雅一点。
我发现这是最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.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
默认情况下-否。
长度属性通常以以下方式用于相同的结果:
if ($(selector).length)
在这里,“选择器”将被您感兴趣的实际选择器替换,无论它是否存在。如果它确实存在,那么length属性将输出一个大于0的整数,因此If语句将变为true,从而执行If块。如果没有,它将输出整数“0”,因此If块不会被执行。
以下是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
}
);