我有一些分组 <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/