503

在 Mootools 中,我只需要运行if ($('target')) { ... }. 在 jQuery 中的工作方式是否if ($('#target')) { ... }相同?

4

11 回答 11

784

正如其他评论者所建议的那样,最有效的方法似乎是:

if ($(selector).length ) {
    // Do something
}

如果你绝对必须有一个 exists() 函数——这会更慢——你可以这样做:

jQuery.fn.exists = function(){return this.length>0;}

然后在你的代码中你可以使用

if ($(selector).exists()) {
    // Do something
}

在这里回答

于 2008-11-18T19:20:29.900 回答
95

不,无论选择器是否匹配,jquery 总是返回一个 jquery 对象。您需要使用 .length

if ( $('#someDiv').length ){

}
于 2008-11-18T19:17:09.160 回答
22

如果您使用:

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }

你会暗示链接是可能的,而不是。

这会更好

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
于 2009-01-14T19:43:58.340 回答
17

我想这里回答的大多数人都不太明白这个问题,否则我可能会弄错。

问题是“如何检查jQuery 中是否存在选择器”。

大多数人认为这是“如何使用 jQuery 检查 DOM 中是否存在元素”。很难互换。

jQuery 允许您创建自定义选择器,但请看这里在初始化之前尝试在 e 上使用时会发生什么;

$(':YEAH');
"Syntax error, unrecognized expression: YEAH"

遇到这个之后,我意识到这只是一个检查的问题

if ($.expr[':']['YEAH']) {
    // Query for your :YEAH selector with ease of mind.
}

干杯。

于 2012-03-18T16:22:10.937 回答
15

还有一种方式:

$('#elem').each(function(){
  // do stuff
});
于 2010-10-22T07:53:37.147 回答
14
if ($('#elem')[0]) {
  // do stuff
}
于 2010-05-27T04:22:51.350 回答
3

或者:

if( jQuery('#elem').get(0) ) {}
于 2008-11-19T09:40:06.110 回答
1

我更喜欢

    if (jQuery("#anyElement").is("*")){...}

它基本上检查这个元素是否是一种“*”(任何元素)。只是更简洁的语法,而“is”在“if”中更有意义

于 2012-08-11T19:50:19.130 回答
1
jQuery.fn.exists = function(selector, callback) {
    var $this = $(this);
    $this.each(function() {
        callback.call(this, ($(this).find(selector).length > 0));
    });
};
于 2014-01-23T13:56:23.183 回答
-3

对我来说.exists不起作用,所以我使用索引:

if ($("#elem").index() ! = -1) {}
于 2012-02-02T12:08:22.510 回答
-6

首先创建一个函数:

$.fn.is_exists = function(){ return document.getElementById(selector) }

然后

if($(selector).is_exists()){ ... }
于 2013-09-30T08:47:38.127 回答