如何使用Jquery为div添加'odd'和'even'类? 我有这个HTML
<div class="carousel" >
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
我需要在'div.item'中添加'odd'和'even'类才能得到这个
<div class="carousel" >
<div class="item odd"></div>
<div class="item even"></div>
<div class="item odd"></div>
<div class="item even"></div>
</div>
答案 0 :(得分:5)
$('.carousel item:odd').addClass('odd');
$('.carousel item:even').addClass('even');
答案 1 :(得分:1)
使用css3:nth-child
$('.carousel .item:nth-child(even)').addClass('even');
$('.carousel .item:nth-child(odd)').addClass('odd');
&#13;
.odd {
color: red;
}
.even {
color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="carousel">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
&#13;
或jQuery odd / even选择器 - 您需要更换班级&amp;选择器,因为在jQuery中索引以0开头
$('.carousel .item:nth-child(even)').addClass('even');
$('.carousel .item:nth-child(odd)').addClass('odd');
&#13;
.odd {
color: red;
}
.even {
color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="carousel">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
&#13;
答案 2 :(得分:1)
您可以使用:odd
和:even
伪选择器。
$('.item:odd').addClass('odd');
$('.item:even').addClass('even');
演示:http://jsfiddle.net/tusharj/tdhbh9un/
:odd
:
选择奇数元素,零索引。
文档:https://api.jquery.com/odd-selector/
:even
:
选择偶数元素,零索引
答案 3 :(得分:0)
试试这个:
$('.carousel item:odd').addClass('odd');
$('.carousel item:even').addClass('even');
答案 4 :(得分:0)
将奇数类分配给偶数,将偶数类分配为奇数将产生所需的结果
那是:
$(".carousel div:even").addClass( "odd" );
AND
$(".carousel div:odd").addClass( "even" );
将产生所需的结果。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Create a polyline using Geolocation and Google Maps API</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".carousel div:even").addClass( "odd" );
$(".carousel div:odd").addClass( "even" );
alert($(".carousel").html());
});
</script>
</head>
<body>
<div class="carousel" >
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</body>
</html>
&#13;