jQuery数据选择器 [英] jquery data selector

查看:83
本文介绍了jQuery数据选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要基于存储在元素的.data()对象中的值来选择元素.至少,我想使用选择器来选择顶级数据属性,也许像这样:

I need to select elements based on values stored in an element's .data() object. At a minimum, I'd like to select top-level data properties using selectors, perhaps like this:

$('a').data("category","music");
$('a:data(category=music)');

或者选择器将采用常规属性选择器格式:

Or perhaps the selector would be in regular attribute selector format:

$('a[category=music]');

或采用属性格式,但带有说明符以指示其位于.data():

Or in attribute format, but with a specifier to indicate it is in .data():

$('a[:category=music]');

我找到了詹姆斯·帕多西的实现方式看起来很简单,但很好.该页面上显示的镜像方法上方的选择器格式.还有一个嘶嘶声.

I've found James Padolsey's implementation to look simple, yet good. The selector formats above mirror methods shown on that page. There is also this Sizzle patch.

由于某种原因,我回想起有一段时间,jQuery 1.4将包括对jquery .data()对象中的值的选择器的支持.但是,现在我正在寻找它,所以找不到了.也许这只是我看到的功能要求.是否有对此的支持,但我只是没有看到它?

For some reason, I recall reading a while back that jQuery 1.4 would include support for selectors on values in the jquery .data() object. However, now that I'm looking for it, I can't find it. Maybe it was just a feature request that I saw. Is there support for this and I'm just not seeing it?

理想情况下,我想使用点表示法支持data()中的子属性.像这样:

Ideally, I'd like to support sub-properties in data() using dot notation. Like this:

$('a').data("user",{name: {first:"Tom",last:"Smith"},username: "tomsmith"});
$('a[:user.name.first=Tom]');

我还想支持多个数据选择器,其中仅找到具有所有指定数据选择器的元素.常规jquery多重选择器执行OR操作.例如,$('a.big, a.small')选择具有bigsmall类的a标签.我正在寻找AND,也许是这样的:

I also would like to support multiple data selectors, where only elements with ALL specified data selectors are found. The regular jquery multiple selector does an OR operation. For instance, $('a.big, a.small') selects a tags with either class big or small). I'm looking for an AND, perhaps like this:

$('a').data("artist",{id: 3281, name: "Madonna"});
$('a').data("category","music");
$('a[:category=music && :artist.name=Madonna]');

最后,如果数据选择器上提供比较运算符和正则表达式功能,那就太好了.因此$(a[:artist.id>5000])是可能的.我意识到我可以使用filter()来完成很多工作,但是拥有一个简单的选择器格式会很好.

Lastly, it would be great if comparison operators and regex features were available on data selectors. So $(a[:artist.id>5000]) would be possible. I realize I could probably do much of this using filter(), but it would be nice to have a simple selector format.

有哪些解决方案可以做到这一点? Jame's Padolsey目前是最好的解决方案吗?我主要关注的是性能,还涉及诸如子属性点符号和多个数据选择器之类的额外功能.是否有其他支持这些功能的实现或在某种程度上更好的实现?

What solutions are available to do this? Is Jame's Padolsey's the best solution at this time? My concern is primarily in regards to performance, but also in the extra features like sub-property dot-notation and multiple data selectors. Are there other implementations that support these things or are better in some way?

推荐答案

我创建了一个新的data选择器,该选择器应使您能够执行嵌套查询和AND条件.用法:

I've created a new data selector that should enable you to do nested querying and AND conditions. Usage:

$('a:data(category==music,artist.name==Madonna)');

模式是:

:data( {namespace} [{operator} {check}]  )

运算符"和检查"是可选的.因此,如果您只有:data(a.b.c),则只需检查a.b.c真实性.

"operator" and "check" are optional. So, if you only have :data(a.b.c) it will simply check for the truthiness of a.b.c.

您可以在下面的代码中看到可用的运算符.其中的~=允许进行正则表达式测试:

You can see the available operators in the code below. Amongst them is ~= which allows regex testing:

$('a:data(category~=^mus..$,artist.name~=^M.+a$)');

我已经对其进行了一些测试,并且看起来效果很好.我可能会很快将其添加为Github存储库(带有完整的测试套件),因此请注意!

I've tested it with a few variations and it seems to work quite well. I'll probably add this as a Github repo soon (with a full test suite), so keep a look out!

代码:

(function(){

    var matcher = /\s*(?:((?:(?:\\\.|[^.,])+\.?)+)\s*([!~><=]=|[><])\s*("|')?((?:\\\3|.)*?)\3|(.+?))\s*(?:,|$)/g;

    function resolve(element, data) {

        data = data.match(/(?:\\\.|[^.])+(?=\.|$)/g);

        var cur = jQuery.data(element)[data.shift()];

        while (cur && data[0]) {
            cur = cur[data.shift()];
        }

        return cur || undefined;

    }

    jQuery.expr[':'].data = function(el, i, match) {

        matcher.lastIndex = 0;

        var expr = match[3],
            m,
            check, val,
            allMatch = null,
            foundMatch = false;

        while (m = matcher.exec(expr)) {

            check = m[4];
            val = resolve(el, m[1] || m[5]);

            switch (m[2]) {
                case '==': foundMatch = val == check; break;
                case '!=': foundMatch = val != check; break;
                case '<=': foundMatch = val <= check; break;
                case '>=': foundMatch = val >= check; break;
                case '~=': foundMatch = RegExp(check).test(val); break;
                case '>': foundMatch = val > check; break;
                case '<': foundMatch = val < check; break;
                default: if (m[5]) foundMatch = !!val;
            }

            allMatch = allMatch === null ? foundMatch : allMatch && foundMatch;

        }

        return allMatch;

    };

}());

这篇关于jQuery数据选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆