Find elements by custom data attribute value

前端 未结 3 443
故里飘歌
故里飘歌 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: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");
    

提交回复
热议问题