Find elements by custom data attribute value

前端 未结 3 444
故里飘歌
故里飘歌 2020-12-22 11:16

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\

相关标签:
3条回答
  • 2020-12-22 11:23
    var resultingElement = $('.b[data-myKey=1234]');
    

    I'm not sure 100% sure, but I think there was an issue with camel-case selectors in data attributes at some point.

    0 讨论(0)
  • 2020-12-22 11:36

    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");
    
    0 讨论(0)
  • 2020-12-22 11:42

    Try this

        $("div.b").filter(function() { 
              return $.data(this, "myKey") == 1234; 
        });
    
    0 讨论(0)
提交回复
热议问题