本文共 1130 字,大约阅读时间需要 3 分钟。
本文翻译自:
This question already has an answer here: 这个问题在这里已有答案:
In Mootools, I'd just run if ($('target')) { ... }
. 在Mootools中,我只运行if ($('target')) { ... }
。 Does if ($('#target')) { ... }
in jQuery work the same way? if ($('#target')) { ... }
jQuery中的if ($('#target')) { ... }
以相同的方式工作吗?
参考:
I prefer the 我更喜欢
if (jQuery("#anyElement").is("*")){...}
Which basically checks if this elements is a kind of "*" (any element). 这基本上检查这些元素是否是一种“*”(任何元素)。 Just a cleaner syntax and the "is" makes more sense inside an "if" 只是一个更清晰的语法和“是”在“如果”内部更有意义
firstly create a function: 首先创建一个函数:
$.fn.is_exists = function(){ return document.getElementById(selector) }
then 然后
if($(selector).is_exists()){ ... }
jQuery.fn.exists = function(selector, callback) { var $this = $(this); $this.each(function() { callback.call(this, ($(this).find(selector).length > 0)); });};
if ($('#elem')[0]) { // do stuff}
no, jquery always returns a jquery object regardless if a selector was matched or not. 不,jquery总是返回一个jquery对象,无论选择器是否匹配。 You need to use .length 你需要使用.length
if ( $('#someDiv').length ){}
转载地址:http://dvcnb.baihongyu.com/