我想用jquery重复添加3个颜色的CSS类到一个长列表标签。我想知道如何实现这一点。还在搞清楚......
在:
<div class="mylist">
<div class="item"><a href="#">record 1</a></div>
<div class="item"><a href="#">record 2</a></div>
<div class="item"><a href="#">record 3</a></div>
<div class="item"><a href="#">record 4</a></div>
<div class="item"><a href="#">record 5</a></div>
<div class="item"><a href="#">record 6</a></div>
<div class="item"><a href="#">record 7</a></div>
<div class="item"><a href="#">record 8</a></div>
</div>
输出:
<div class="mylist">
<div class="item"><a href="#" class="color1">record 1</a></div>
<div class="item"><a href="#" class="color2">record 2</a></div>
<div class="item"><a href="#" class="color3">record 3</a></div>
<div class="item"><a href="#" class="color1">record 4</a></div>
<div class="item"><a href="#" class="color2">record 5</a></div>
<div class="item"><a href="#" class="color3">record 6</a></div>
<div class="item"><a href="#" class="color1">record 7</a></div>
<div class="item"><a href="#" class="color2">record 8</a></div>
</div>
答案 0 :(得分:4)
为什么在使用CSS和:nth-child进行此操作时需要jQuery?
.item:nth-child(3n+1) {
background-color:red;
}
.item:nth-child(3n+2) {
background-color:green;
}
.item:nth-child(3n+3) {
background-color:blue;
}
<div class="mylist">
<div class="item"><a href="#">record 1</a></div>
<div class="item"><a href="#">record 2</a></div>
<div class="item"><a href="#">record 3</a></div>
<div class="item"><a href="#">record 4</a></div>
<div class="item"><a href="#">record 5</a></div>
<div class="item"><a href="#">record 6</a></div>
<div class="item"><a href="#">record 7</a></div>
<div class="item"><a href="#">record 8</a></div>
</div>
答案 1 :(得分:0)
试试这个: -
var i=1;
$('div.item a').each(function(){
$(this).attr('class','color'+i)
if(i==3){
i=0;
}
i++;
});
答案 2 :(得分:0)
你可以试试这个,
var tempVar = 1;
$('.mylist.item').each(function(){
if( tempVar > 3 )
tempVar = 1;
$( this ).find( "a" ).addClass( "color"+tempVar );
tempVar++;
});
答案 3 :(得分:0)
使用jquery
,
$('div.item a').each(function(index){
$(this).addClass('color'+(index%3+1));
});
$('div.item a').each(function(index){
$(this).addClass('color'+(index%3+1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mylist">
<div class="item"><a href="#">record 1</a></div>
<div class="item"><a href="#">record 2</a></div>
<div class="item"><a href="#">record 3</a></div>
<div class="item"><a href="#">record 4</a></div>
<div class="item"><a href="#">record 5</a></div>
<div class="item"><a href="#">record 6</a></div>
<div class="item"><a href="#">record 7</a></div>
<div class="item"><a href="#">record 8</a></div>
</div>