在Mootools中,我只需要运行if ($('target')){…}。if ($('#target')){…}在jQuery的工作方式相同?
当前回答
我更喜欢
if (jQuery("#anyElement").is("*")){...}
它基本上检查这个元素是否是一种“*”(任何元素)。 更简洁的语法,is在if中更有意义
其他回答
if ($('#elem')[0]) {
// do stuff
}
另外:
if( jQuery('#elem').get(0) ) {}
对我来说,.exists不起作用,所以我使用索引:
if ($("#elem").index() ! = -1) {}
我更喜欢
if (jQuery("#anyElement").is("*")){...}
它基本上检查这个元素是否是一种“*”(任何元素)。 更简洁的语法,is在if中更有意义
jQuery.fn.exists = function(selector, callback) {
var $this = $(this);
$this.each(function() {
callback.call(this, ($(this).find(selector).length > 0));
});
};