如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
我看到这里的大多数答案都不准确,他们检查了元素长度,在很多情况下都可以,但不是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
其他回答
如果您使用
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
你会暗示链接是可能的,而不是可能的。
这样会更好:
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
或者,从常见问题解答:
if ( $('#myDiv').length ) { /* Do something */ }
您也可以使用以下选项。如果jQuery对象数组中没有值,那么获取数组中的第一个项将返回undefined。
if ( $('#myDiv')[0] ) { /* Do something */ }
这与所有答案非常相似,但为什么不使用!运算符两次,这样可以得到布尔值:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
只需检查选择器的长度,如果它大于0,则返回true,否则返回false。
对于ID:
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
对于类别:
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
对于下拉列表:
if( $('#selector option').size() ) { // use this if you are using dropdown size to check
// it exists
}
你可以使用这个:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*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]) ...;