使用 jQuery 的 Sizzle 引擎查找类(高级)

发布于 2024-08-18 02:18:20 字数 905 浏览 5 评论 0原文

我试图做的是查看 jQuery 对象甚至 DOM 元素是否包含使用与 Sizzle 引擎相同的选择器的特定类。

jQuery 通过以下方式公开公开 Sizzle:

jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;

我可以成功地使用 find 方法来确定特定 DOM 元素具有与我的选择器匹配的类,但我似乎无法找到一种方法来访问匹配的选择器的名称。

示例(未按预期工作)

$.fn.extend({
    getMatchingClass: function(selector) {
        return this.each(function() {
            var match = jQuery.find.matches('*[class'+selector+']', [this]);
                    // I would like to return the matching class's FULL NAME,
                    // i.e. lightbox_RESTOFCLASS
            alert(match[0]);
        });
    }
});

var class = $('#lightbox').getMatchingClass('^="lightbox_"');

是否可以使用 Sizzle 返回与我的选择器匹配的类名?

What I am attempting to do is see if a jQuery object (or even DOM element for that matter) contains a particular class using the same selectors as the Sizzle engine.

jQuery publicly exposes Sizzle with the following:

jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;

I can successfully use the find method to determine that a particular DOM element has a class matching my selector but I cannot seem to find a way to get access to the name of the selector that matched.

EXAMPLE (NOT WORKING AS INTENDED)

$.fn.extend({
    getMatchingClass: function(selector) {
        return this.each(function() {
            var match = jQuery.find.matches('*[class'+selector+']', [this]);
                    // I would like to return the matching class's FULL NAME,
                    // i.e. lightbox_RESTOFCLASS
            alert(match[0]);
        });
    }
});

var class = $('#lightbox').getMatchingClass('^="lightbox_"');

Is it possible to use Sizzle to return the class name which matched my selector?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

苄①跕圉湢 2024-08-25 02:18:20

您可以使用 jQuery 库的 attr( name ) 函数。

您可以修改原始函数,将选择器和属性作为参数来应用它。这样您就可以查询指定属性值的结果。

$.fn.extend({
    getMatchingClass: function(attribute, selector) {
        return this.each(function() {
            var match = jQuery.find.matches('*['+attribute+selector+']', [this]);
                    // I would like to return the matching class's FULL NAME,
                    // i.e. lightbox_RESTOFCLASS
            alert( $(match[0]).attr(attribute) );
        });
    }
});

请记住,选择器可能会匹配多个类。那你想要哪个结果呢?所有匹配的列表?或者只是第一个(作为示例中的警报值)

[编辑],尽管您在一个项目上有多个类别的情况,但这并没有考虑在内。

You could use the attr( name ) function of the jQuery library ..

You could modify your original function to take as parameters both the selector and the attribute to apply it to .. this way you can query the results for the specified attribute value.

$.fn.extend({
    getMatchingClass: function(attribute, selector) {
        return this.each(function() {
            var match = jQuery.find.matches('*['+attribute+selector+']', [this]);
                    // I would like to return the matching class's FULL NAME,
                    // i.e. lightbox_RESTOFCLASS
            alert( $(match[0]).attr(attribute) );
        });
    }
});

Keep in mind that the selector might match more than one classes. Which result would you want then? a list of all matches ? or just the first (as the alerted value in the example)

[edit] this does not take into account though the case where you have more than one class on an item ..

乖乖哒 2024-08-25 02:18:20

当然,您的选择器不必是“li”,它可以是您所了解的有关要选择的项目的任何标准。但要获取整个类属性,只需使用 .attr("class") 选择器。像这样

$(document).ready(function(){
    $("li").each(function (i) {
        var class = $(this).attr("class");
            alert(class);
    });
});

of course your selector doesnt have to be "li" it can be whatever criteria you do know about the items you want to select. but to get the entire class attribute, just use the .attr("class") selector. like this

$(document).ready(function(){
    $("li").each(function (i) {
        var class = $(this).attr("class");
            alert(class);
    });
});
度的依靠╰つ 2024-08-25 02:18:20

现在我更好地理解了您的问题,您是否尝试过使用 原生 Sizzle 选择器去做你想做的事?

包含单词选择器应该可以满足您的需求:

$('#lightbox').find("[class~='lightbox']");

一旦您有了该元素,您就可以通过调用 attr(...) 轻松获取类名:

var className = $('#lightbox').find("[class~='lightbox_']").attr('class');

这只会为您提供整个类属性,而不是该元素的各个类。您必须 split(' ') className 才能获取各个类并找到匹配的类。

function getSimilarClass(className, searchString) {
    var classes = className.split(' ');
    for(var i = 0; i < classes.length; i++) {
        if (classes[i].indexOf(searchString) != -1) {
            return classes[i];
        }
    }
    return null;
}
var className = $('#lightbox').find("[class~='lightbox_']").attr('class');
var match = getSimilarClass(className, "lightbox_");

然而,这个过程有缺陷,因为可能有多个具有相似类的标签,这是无法解释的,并且单个标签可能有多个具有相似名称的类。

Now that I better understand your question, have you tried using native Sizzle selectors to do what you're trying to do?

The contains word selector should do what you're looking for:

$('#lightbox').find("[class~='lightbox']");

Once you have the element, you can then easily get the class name by calling attr(...):

var className = $('#lightbox').find("[class~='lightbox_']").attr('class');

This will only give you the entire class attribute, not the individual classes for the element. You'd have to split(' ') the className to get the individual classes and find a matching class.

function getSimilarClass(className, searchString) {
    var classes = className.split(' ');
    for(var i = 0; i < classes.length; i++) {
        if (classes[i].indexOf(searchString) != -1) {
            return classes[i];
        }
    }
    return null;
}
var className = $('#lightbox').find("[class~='lightbox_']").attr('class');
var match = getSimilarClass(className, "lightbox_");

This process has flaws however, since there could be multiple tags with similar classes, which this won't account for, and individual tags could potentially have several classes with similar names.

仅冇旳回忆 2024-08-25 02:18:20

我想出了一个使用选择器子集(^=$=*=的非嘶嘶声解决方案>=) 完全正常工作。不过,如果有一个 Sizzle 解决方案就好了。这至少应该展示插件的预期功能应该做什么。

$.fn.getMatchingClass = function(selector) {
    var regex, class, tmp, $this;
    tmp = $(this)[0].className;
    class = selector;
    class = class.replace(/(\^|\*|\$)?=/i, '');
    class = class.replace(/\"/g, '');
    if (selector.indexOf('$=') != -1) {
        regex = new RegExp('[\\s]+' + class + '
, 'i');
    } else if (selector.indexOf('^=') != -1) {
        regex = new RegExp('^' + class + '[\\s]+', 'i');
    } else if (selector.indexOf('*=') != -1) {
        regex = new RegExp('[a-zA-z0-9_\\-]*' + class + '[a-zA-z0-9_\\-]*', 'gi');
    } else if (selector.indexOf('=') != -1) {
        regex = new RegExp('^' + class + '
, 'i');
    } else return false;
    return tmp.match(regex);
}

var class = $('#myID').getMatchingClass('*="lightbox"');
var class2 = $('#myID').getMatchingClass('^=lightbox');
var class3 = $('#myID').getMatchingClass('="lightbox"');
var class4 = $('#myID').getMatchingClass('$=lightbox');
alert(class);
alert(class2);
alert(class3);
alert(class4);

I've come up with a non-sizzle solution using a subset of selectors (^=, $=, *=, and =) which is fully working. A Sizzle solution would have been nice, however. This should at least demonstrate what the intended functionality of the plugin should do.

$.fn.getMatchingClass = function(selector) {
    var regex, class, tmp, $this;
    tmp = $(this)[0].className;
    class = selector;
    class = class.replace(/(\^|\*|\$)?=/i, '');
    class = class.replace(/\"/g, '');
    if (selector.indexOf('$=') != -1) {
        regex = new RegExp('[\\s]+' + class + '
, 'i');
    } else if (selector.indexOf('^=') != -1) {
        regex = new RegExp('^' + class + '[\\s]+', 'i');
    } else if (selector.indexOf('*=') != -1) {
        regex = new RegExp('[a-zA-z0-9_\\-]*' + class + '[a-zA-z0-9_\\-]*', 'gi');
    } else if (selector.indexOf('=') != -1) {
        regex = new RegExp('^' + class + '
, 'i');
    } else return false;
    return tmp.match(regex);
}

var class = $('#myID').getMatchingClass('*="lightbox"');
var class2 = $('#myID').getMatchingClass('^=lightbox');
var class3 = $('#myID').getMatchingClass('="lightbox"');
var class4 = $('#myID').getMatchingClass('$=lightbox');
alert(class);
alert(class2);
alert(class3);
alert(class4);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文