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

JavaScript

6的不行

2020-03-13

在Mootools中,我只是跑步if ($('target')) { ... }if ($('#target')) { ... }jQuery中的工作方式是否相同?

第1444篇《您如何检查选择器是否匹配jQuery中的某些内容?\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
OU 2020.03.13

firstly create a function:

$.fn.is_exists = function(){ return document.getElementById(selector) }

then

if($(selector).is_exists()){ ... }
老丝Jim猴子 2020.03.13
jQuery.fn.exists = function(selector, callback) {
    var $this = $(this);
    $this.each(function() {
        callback.call(this, ($(this).find(selector).length > 0));
    });
};
梅猪猪 2020.03.13

我更喜欢

    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"

米亚Near 2020.03.13

如果您使用过:

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }

您将暗示,不可能时可以进行链接。

这样会更好

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
Sam前端 2020.03.13

正如其他评论者所建议的那样,最有效的方法似乎是:

if ($(selector).length ) {
    // Do something
}

如果您绝对必须具有一个exist()函数-这会变慢-您可以执行以下操作:

jQuery.fn.exists = function(){return this.length>0;}

然后,您可以在代码中使用

if ($(selector).exists()) {
    // Do something
}

这里回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android