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


当前回答

我更喜欢

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

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

其他回答

首先创建一个函数:

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

then

if($(selector).is_exists()){ ... }

还有另一种方式:

$('#elem').each(function(){
  // do stuff
});
jQuery.fn.exists = function(selector, callback) {
    var $this = $(this);
    $this.each(function() {
        callback.call(this, ($(this).find(selector).length > 0));
    });
};

我更喜欢

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

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

如果你使用:

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

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

这样会更好

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