本文翻译自:How do you check if a selector matches something in jQuery? [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- Is there an “exists” function for jQuery? jQuery是否存在“存在”功能? 40 answers 40个答案
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')) { ... }
以相同的方式工作吗?
#1楼
参考:https://stackoom.com/question/1FzW/你如何检查选择器是否匹配jQuery中的内容-重复
#2楼
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" 只是一个更清晰的语法和“是”在“如果”内部更有意义
#3楼
firstly create a function: 首先创建一个函数:
$.fn.is_exists = function(){ return document.getElementById(selector) }
then 然后
if($(selector).is_exists()){ ... }
#4楼
jQuery.fn.exists = function(selector, callback) {
var $this = $(this);
$this.each(function() {
callback.call(this, ($(this).find(selector).length > 0));
});
};
#5楼
if ($('#elem')[0]) {
// do stuff
}
#6楼
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 ){
}