在Mootools中,我只需要运行if ($('target')){…}。if ($('#target')){…}在jQuery的工作方式相同?
当前回答
如果你使用:
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
你可能会暗示链条是可能的,但实际上不是。
这样会更好
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
其他回答
不,无论选择器是否匹配,jquery总是返回一个jquery对象。 你需要使用。length
if ( $('#someDiv').length ){
}
正如其他评论者所建议的,最有效的方法似乎是:
if ($(selector).length ) {
// Do something
}
如果你绝对必须有一个exists()函数-这会比较慢-你可以这样做:
jQuery.fn.exists = function(){return this.length>0;}
然后在代码中使用
if ($(selector).exists()) {
// Do something
}
如这里所回答的
首先创建一个函数:
$.fn.is_exists = function(){ return document.getElementById(selector) }
then
if($(selector).is_exists()){ ... }
另外:
if( jQuery('#elem').get(0) ) {}
如果你使用:
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
你可能会暗示链条是可能的,但实际上不是。
这样会更好
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }