简体   繁体   中英

Using jQuery to select first elements with distinct data-attribute

I've got a ul of various items which can have one of several possible data-attribute values, like this:

<ul>
    <li id="li1" data-cat="one">test item
    <li id="li2" data-cat="one">test no 2
    <li id="li3" data-cat="two">test dummy
    <li id="li4" data-cat="three">test no 4
    <li id="li5" data-cat="three">more test
    <li id="li6" data-cat="three">test no 6
</ul>

I'm attempting to use jQuery to select the first item of each distinct data-cat value - so for this example, li#li1 , li#li3 , and li#li4 . I've tried building an array of each element with the data-attribute , then sorting with .unique like this

var list = $( '[data-cat]' ).get();
listSorted = jQuery.unique( list );
$( listSorted ).addClass('active');

But the code just selected all elements ( see fiddle here )

I've found answers on SO like this one that come close, but they all seem to rely on knowing the data-attribute value beforehand and searching for that specific value. Is it possible to select the first element with a particular data-cat value without specifying the values beforehand?

var cats = {};
var list = $( '[data-cat]' ).filter(function(){
    var category = $(this).data("cat");

    if(cats[category]){
        // category already accounted for, return false
        return false;   
    } else {
        // first of this category
        cats[category] = true;
        return true;
    }
});

http://jsfiddle.net/nB3ru/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM