在Mootools中,我只需要运行if ($('target')){…}。if ($('#target')){…}在jQuery的工作方式相同?
当前回答
首先创建一个函数:
$.fn.is_exists = function(){ return document.getElementById(selector) }
then
if($(selector).is_exists()){ ... }
其他回答
另外:
if( jQuery('#elem').get(0) ) {}
我想这里回答的大多数人都不太理解这个问题,否则我可能会弄错。
问题是“如何检查jQuery中是否存在选择器”。
大多数人认为这是“如何使用jQuery检查DOM中是否存在元素”。几乎可以互换。
jQuery允许你创建自定义选择器,但是当你在初始化e之前尝试使用它时会发生什么;
$(':YEAH');
"Syntax error, unrecognized expression: YEAH"
在遇到这种情况后,我意识到这只是一个简单的检查问题
if ($.expr[':']['YEAH']) {
// Query for your :YEAH selector with ease of mind.
}
欢呼。
jQuery.fn.exists = function(selector, callback) {
var $this = $(this);
$this.each(function() {
callback.call(this, ($(this).find(selector).length > 0));
});
};
首先创建一个函数:
$.fn.is_exists = function(){ return document.getElementById(selector) }
then
if($(selector).is_exists()){ ... }
if ($('#elem')[0]) {
// do stuff
}