我在我的网页中有一些分组的<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个组(数据组),并添加一个名为'edge‘的CSS类到它的所有<li>标签使用jQuery或添加一个CSS属性使用第n。
请帮我解决这个问题。
感谢并致以问候
发布于 2013-02-08 03:34:01
更新
您不能简单地使用选择器。您必须遍历所有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');
});发布于 2013-02-08 03:34:28
所以就像这样:
$('li[data-group="four"]').each(function(){
$(this).addClass('edge');
});你是这个意思吗?
所以更像是:
function processItems(items){
items.each(function(){
$(this).addClass('edge');
});
}
processItems($('li[data-group="four"]'));
processItems($('li[data-group="eight"]'));
processItems($('li[data-group="twelve"]'));我不知道这样做是否会提高性能,但循环遍历每个li项可能会很糟糕,速度也会很慢,这取决于列表中它们的数量。这里没有说我拥有的是最好的方法,但是如果你有数百个li项,你的循环可能会运行得很慢。
https://stackoverflow.com/questions/14759411
复制相似问题