在Mootools中,我只需要运行if ($('target')){…}。if ($('#target')){…}在jQuery的工作方式相同?
当前回答
另外:
if( jQuery('#elem').get(0) ) {}
其他回答
还有另一种方式:
$('#elem').each(function(){
// do stuff
});
if ($('#elem')[0]) {
// do stuff
}
不,无论选择器是否匹配,jquery总是返回一个jquery对象。 你需要使用。length
if ( $('#someDiv').length ){
}
首先创建一个函数:
$.fn.is_exists = function(){ return document.getElementById(selector) }
then
if($(selector).is_exists()){ ... }
对我来说,.exists不起作用,所以我使用索引:
if ($("#elem").index() ! = -1) {}