按自定义数据属性值查找元素 [英] Find elements by custom data attribute value

查看:78
本文介绍了按自定义数据属性值查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法根据jQuery(+ jQuery UI lib)的数据属性值使用javascript选择一个项目(div,span,等等..)。例如,假设我有:

I was wondering if there's a way to select an item (div,span,whatever..) using javascript with jQuery (+ jQuery UI lib) based on its data attribute value. For example, let's say I have:

<div class="b">Hi</div>

然后我将一些数据分配给它:

I then assign some data to it:

$('.b').data('myKey', 1234);

然后,我想找到满足条件myKey = 1234的div(或多个div)。
例如,像这样:

Then, I want to find a div (or multiple divs that) satisfy condition myKey = 1234 . For example, like this:

var resultingElement = $('.b:data(myKey=1234)');

默认是可行的,还是我必须自己实现这种选择器?
不,我不想为此使用HTML5的可见数据 - *属性。

Is it possible by default, or do I have to implement this kind of selector myself? And no, I don't want to use HTML5's visible data-* attributes for this.

推荐答案

你可以创建一个自定义伪选择器以简化操作: http://jsfiddle.net/g2xKB/1/

You can create a custom pseudo-selector to make things easy: http://jsfiddle.net/g2xKB/1/.

$.expr.pseudos.data = $.expr.createPseudo(function(args) {
    var items = args.split(",");  // the arguments (key, value)

    $.each(items, function(i, item) {
        item = item.trim();
        var isString = /^['"]|['"]$/.test(item);
        item = item.replace(/^['"]|['"]$/g, "");  // remove quotes

        if(!isString) {
            item = +item;  // if no quotes, it's a number
        }

        items[i] = item;
    });

    return function(elem) {
        return $.data(elem, items[0]) === items[1];
    }
});

然后您可以按如下方式使用它:

You can then use it as follows:

$(".b:data('myKey', 1234)").css("color", "red");

这篇关于按自定义数据属性值查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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