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


当前回答

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

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

}

其他回答

jQuery.fn.exists = function(selector, callback) {
    var $this = $(this);
    $this.each(function() {
        callback.call(this, ($(this).find(selector).length > 0));
    });
};

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

if ($("#elem").index() ! = -1) {}

如果你使用:

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

你可能会暗示链条是可能的,但实际上不是。

这样会更好

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

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

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

}
if ($('#elem')[0]) {
  // do stuff
}