如何检查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]) ...;
其他回答
不,没有这样的方法。但是您可以为自己的jQuery扩展jQuery。目前(2022年)的做法是:
jQuery.fn.extend({
exists() { return !!this.length }
});
Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
这是对杰夫·阿特伍德主持的《放牧守则》播客的回应
这与所有答案非常相似,但为什么不使用!运算符两次,这样可以得到布尔值:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
试试这个。
简单、简短,可在整个项目中使用:
jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin
用法:
console.log($("element-selector").exists());
_________________________________
或更短:(当您不想定义jQuery插件时):
if(!!$("elem-selector")[0]) ...;
甚至
if($("elem-selector")[0]) ...;
我偶然发现了这个问题,我想分享一段我目前使用的代码:
$.fn.exists = function(callback) {
var self = this;
var wrapper = (function(){
function notExists () {}
notExists.prototype.otherwise = function(fallback){
if (!self.length) {
fallback.call();
}
};
return new notExists;
})();
if(self.length) {
callback.call();
}
return wrapper;
}
现在我可以编写这样的代码了-
$("#elem").exists(function(){
alert ("it exists");
}).otherwise(function(){
alert ("it doesn't exist");
});
它可能看起来有很多代码,但当用CoffeeScript编写时,它非常小:
$.fn.exists = (callback) ->
exists = @length
callback.call() if exists
new class
otherwise: (fallback) ->
fallback.call() if not exists