1

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

<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

4 回答 4

3

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

var $divs = $('div');

$divs.filter(':odd').attr('class', 'odd');
$divs.filter(':even').attr('class', 'even');
于 2012-09-21T22:11:19.337 回答
3

这应该这样做

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

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

于 2012-09-21T22:11:49.990 回答
1

或这个:

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

JsFiddle 示例:

http://jsfiddle.net/2VpgV/

于 2012-09-21T22:13:09.507 回答
0

您应该使用事件委托|:

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

下面是一个事件委托机制的例子:

$(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>

于 2012-09-21T23:06:29.980 回答