如何使用jQuery遍历一组元素并设置奇数/偶数类?

时间:2012-09-21 22:08:48

标签: jquery html

我有一个像这样的元素列表:

<div class="odd">1</div>
<div class="even">2</div>
<div class="odd">3</div>
<div class="even">4</div>

现在,当用户删除元素3时,结果为:

<div class="odd">1</div>
<div class="even">2</div>
<div class="even">4</div>

现在我希望jQuery从第一个元素转到最后一个元素并重新定义类:

<div class="odd">1</div>
<div class="even">2</div>
<div class="odd">4</div>

我不确定如何处理这个问题。

4 个答案:

答案 0 :(得分:3)

您可以使用:odd:even选择器:

var $divs = $('div');

$divs.filter(':odd').attr('class', 'odd');
$divs.filter(':even').attr('class', 'even');

答案 1 :(得分:3)

这应该这样做

$("div").removeClass('odd even');
$("div:odd").addClass('odd');
$("div:even").addClass('even');

只删除.odd或.even类,你添加的任何其他类(除了.odd和.even)都将“存活”。

答案 2 :(得分:1)

或者这个:

$('div:odd').attr('class', 'odd');
$('div:even').attr('class', 'even');

JsFiddle示例:

http://jsfiddle.net/2VpgV/

答案 3 :(得分:0)

您应该使用 event delegation |:

  

事件委托允许我们将单个事件侦听器附加到父元素,该元素将为匹配选择器的所有后代触发,无论这些后代现在是存在还是将来添加。

以下是事件委托机制的示例:

$(function(){
    $('#container').on('click', '.btn', function(e){
           $(this).parent().nextAll().each(function(i,el){
             var $t = $(this);
               $t.attr('class', $t.is('.odd') ? 'even':'odd');
           }).end().remove();
    });
});
.odd{background-color:red}
.even{background-color:green}
.btn{text-decoration:underline;font-style:italic;padding:2px;display:inline-block;cursor:pointer;margin:2px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="odd">
    1<span class="btn" title="remove the line and fix siblings class">remove line</span>
  </div>
  <div class="even">
    2<span class="btn" title="remove the line and fix siblings class">remove line</span>
  </div>
  <div class="odd">
    3<span class="btn" title="remove the line and fix siblings class">remove line</span>
  </div>
  <div class="even">
    4<span class="btn" title="remove the line and fix siblings class">remove line</span>
  </div>
  <div class="odd">
    5<span class="btn" title="remove the line and fix siblings class">remove line</span>
  </div>
  <div class="even">
    6<span class="btn" title="remove the line and fix siblings class">remove line</span>
  </div>
  <div class="odd">
    7<span class="btn" title="remove the line and fix siblings class">remove line</span>
  </div>
  <div class="even">
    8<span class="btn" title="remove the line and fix siblings class">remove line</span>
  </div>
</div>