如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
如果输入不存在,它将没有值。试试这个。。。
if($(selector).val())
其他回答
检查元素的存在在jQuery官方网站中有完整的文档记录!
使用选择器:if($(“#myDiv”).length){$(“#myDiv”).show();}注意,并不总是需要测试元素是否存在。下面的代码将显示元素(如果存在),并且不做任何操作(无错误)如果没有:$(“#myDiv”).show();
在JavaScript中,一切都是“truthy”或“falsy”,对于数字0表示假,其他一切都是真。所以你可以写:
if ($(selector).length)
你不需要那>0部分。
Yes!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
这是对杰夫·阿特伍德主持的《放牧守则》播客的回应
我使用的是:
if($("#element").length > 0){
//the element exists in the page, you can do the rest....
}
它非常简单,很容易找到元素。
我看到这里的大多数答案都不准确,他们检查了元素长度,在很多情况下都可以,但不是100%,想象一下如果数字传递给函数,所以我原型化了一个函数,它检查所有条件并返回应该的答案:
$.fn.exists = $.fn.exists || function() {
return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement));
}
这将检查长度和类型,现在您可以这样检查:
$(1980).exists(); //return false
$([1,2,3]).exists(); //return false
$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
$([{nodeName: 'foo'}]).exists() // returns false
$('div').exists(); //return true
$('.header').exists(); //return true
$(document).exists(); //return true
$('body').exists(); //return true