JS删除类后,CSS nth-of-type不会更新

时间:2013-08-15 05:11:30

标签: javascript css css3

我已经创建了以下的JSFiddle:http://jsfiddle.net/qTLmV/

这是我正在使用的CSS:

.nested > .addable-group > div.active:nth-of-type(even) {
  background: blue;
}

.nested > .addable-group > div.active:nth-of-type(odd) {
  background: grey;
}

简化布局:

<div class="nested">
  <div class="addable-group">
    <div class="active"><a href="#">remove 1</a></div>
    <div class="active"><a href="#">remove 2</a></div>
    <div class="active"><a href="#">remove 3</a></div>
    <div class="active"><a href="#">remove 4</a></div>
  </div>
</div>

JS

$(document).on("click", "a", function(event) {
  var container = $(this).parent();
  container.hide();
  container.removeClass("active");
  //container.remove();
  return event.preventDefault();
});

我要做的是,如果点击任何“删除”链接,他们应该被隐藏,删除他们的“活动”类,并且交替的背景颜色应该保持一致。但是,我无法让这个工作。如果我完全删除DOM元素它可以工作,但只是删除类不。

我不想完全删除DOM元素,因为在实时应用中,它们包含表单字段,在提交时,从数据库中删除该元素的记录。

有什么我想念的吗?

编辑:作为一个快速而肮脏的解决方案,我最终只是将“已移除”的项目移到了组的底部:http://jsfiddle.net/qTLmV/2/

2 个答案:

答案 0 :(得分:4)

:nth-of-type()不查看类,它只查看元素类型。 .addable-group的所有孩子都是div个元素,并且您是否有.active个班级并不改变其中第div个孩子的事实.addable-group

如果你只需要根据.active类来设置这些元素的样式,我恐怕你需要使用JS和样式来应用不同的类。

答案 1 :(得分:-1)

$(document).on("click", "a", function(event) {
    var container = $(this).parent();
    $(this).remove();
    container.remove();    
});
相关问题