简体   繁体   English

使用jQuery选择具有不同数据属性的第一个元素

[英]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各个项目可以有几种可能的一个data-attribute值,就像这样:

<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 . 我试图使用jQuery选择每个不同的第一项 data-cat 价值 -所以在这个例子中, li#li1li#li3li#li4 I've tried building an array of each element with the data-attribute , then sorting with .unique like this 我尝试过使用data-attribute为每个元素构建一个数组,然后像这样使用.unique进行排序

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. 我已经找到了类似这样的答案,但是它们似乎都依赖于事先了解data-attribute值并搜索该特定值。 Is it possible to select the first element with a particular data-cat value without specifying the values beforehand? 是否可以在不事先指定值的情况下选择具有特定data-cat值的第一个元素?

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/ http://jsfiddle.net/nB3ru/5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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