开发者

unique attribute values with jquery

is there a way to get all the unique values for a certain attribute.

e.g

<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="dog">&开发者_如何学运维lt;/div>
<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="cat"></div>
<div class="bob" data-xyz="fish"></div>

I need to get all the distinct values for data-xyz attribute on div.bob,

so it should return fish, dog and cat.


Small code: Create an object and make 'dog' 'fish' 'cat' properties. That will make them unique. Then get the unique property names from the object. Simple and easy:

var items = {};
$('div.bob').each(function() {
    items[$(this).attr('data-xyz')] = true; 
});

var result = new Array();
for(var i in items)
{
    result.push(i);
}
alert(result);

http://jsfiddle.net/GxxLj/1/


Keep track of which values you have already processed:

var seen = {};

var values = $('div.bob').map(function() {
    var value = this.getAttribute('data-xyz');
    // or $(this).attr('data-xyz');
    // or $(this).data('xyz');

    if(seen.hasOwnProperty(value)) return null;

    seen[value] = true;
    return value;
}).get();

Reference: $.map()

This, of course, only works with primitive values. In case you are mapping to objects, you'd have to override the toString() method of the objects so that they can be used as keys.

Or as plugin:

(function($) {

    $.fn.map_unique = function(callback) {
        var seen = {};
        function cb() {
            var value = callback.apply(this, arguments);
            if(value === null || seen.hasOwnProperty(value)) {
                return null;
            }
            seen[value] = true;
            return value;
        }
        return this.map(cb);
    });

}(jQuery));


var array = $('div.bob').map(function() { return $(this).data('xyz'); });

That will return all values. Then you can run it through a unique function.

How do I make an array with unique elements (i.e. remove duplicates)?

function ArrNoDupe(a) {
    var temp = {};
    for (var i = 0; i < a.length; i++)
        temp[a[i]] = true;
    var r = [];
    for (var k in temp)
        r.push(k);
    return r;
}
array = ArrNoDupe(array);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜