如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
如果输入不存在,它将没有值。试试这个。。。
if($(selector).val())
其他回答
在JavaScript中,一切都是“truthy”或“falsy”,对于数字0表示假,其他一切都是真。所以你可以写:
if ($(selector).length)
你不需要那>0部分。
不,没有这样的方法。但是您可以为自己的jQuery扩展jQuery。目前(2022年)的做法是:
jQuery.fn.extend({
exists() { return !!this.length }
});
我偶然发现了这个问题,我想分享一段我目前使用的代码:
$.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
在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>