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


当前回答

首先创建一个函数:

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

then

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

其他回答

如果你使用:

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

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

这样会更好

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

首先创建一个函数:

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

then

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

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

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

}

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

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

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

jQuery允许你创建自定义选择器,但是当你在初始化e之前尝试使用它时会发生什么;

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

在遇到这种情况后,我意识到这只是一个简单的检查问题

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

欢呼。

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

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