你如何检查选择器是否匹配jQuery中的内容? [重复]

本文翻译自:How do you check if a selector matches something in jQuery? [duplicate]

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')) { ... }以相同的方式工作吗?


#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 ){

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值