jquery - 选择某些元素组

标签 jquery html css css-selectors

我有一些分组 <li>在我的网页中标记如下。

<ul id="dg">
   <!-- group-1 -->
   <li data-group="one">....</li>
   <li data-group="one">....</li>
   <li data-group="one">....</li>
   <li data-group="one">....</li>

   <!-- group-2 -->
   <li data-group="two">....</li>
   <li data-group="two">....</li>

   <!-- group-3 -->
   <li data-group="three">....</li>

   <!-- group-4 -->
   <li data-group="four">....</li>
   <li data-group="four">....</li>
   <li data-group="four">....</li>
</ul>

同样,我有大约 20 个(动态的)组 <li>使用“数据组”分类的标签。每个类别都有不同数量的 <li>标签。

我想做的是,我想选择每第 4 个组(数据组)并向其所有 <li> 添加一个名为“edge”的 CSS 类使用 jQuery 标记或使用 nth 添加 CSS 属性。

请帮我解决这个问题。

感谢和问候

最佳答案

更新

您不能简单地使用选择器。您必须遍历所有 li 并推断它们是否属于您想要的组

var currentGroup = ""; //Name of the group currently checked 
var counter = 0; //Number of group found

//Loop through the items
$('#dg li').each(function(){
    //Check if we are checking a new group
    if(currentGroup != $(this).attr('data-group'))
    {
        //If yes, save the name of the new group
        currentGroup = $(this).attr('data-group');
        //And increment the number of group found
        counter++;
    }

    //If the number of the group is a multiple of 4, add the class you want
    if((counter % 4) == 0)
        $(this).addClass('edge');
});

关于jquery - 选择某些元素组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14759411/

相关文章:

javascript - Ajax 插入的内容在 DOM 中无法访问

javascript - $ ("<div/>").text(value).html 不是函数错误

html - 将 Bootstrap 导航栏内的图像垂直对齐到基线

html - 如何在 Bootstrap 中将图像放入全高列?

html - 为什么我的图像在使用 'margin: 0 auto' 时不居中

css - 在 Bootstrap 3 中切换到小屏幕上的流体布局

CSS 选择器优先级

javascript - 包含特定类的 div 的 jquery 选择器

jquery - 如何保存jquery选择器以供以后使用

javascript - 在 jQuery 或 CSS 中隐藏所有 rowspan 列单元格