第 n 个子 CSS 在使用 jQuery 删除行时不会重绘

nth-child css doesn't redraw when removing a row with jquery

本文关键字:删除行 jQuery 个子 CSS      更新时间:2023-09-26

我有一个jsfiddle在这里演示了这个问题:http://jsfiddle.net/xjmwY/

基本上,我有一个使用第 n 个子(奇数)规则的 css3 斑马条纹表。

.myTable tr {
    background-color: #efefef;
}
.myTable  tr:nth-child(odd) {
    background-color: #fff;
}

当通过 jquery 删除一行时,我最终会得到两个颜色相同的后续行。有没有办法让桌子重新粉刷?

.fadeOut()只是隐藏该行(将其淡化为透明,然后将显示设置为无),但它并没有真正删除它。为此,请使用.remove()

$("tr").click(function(event) {
  event.preventDefault();
  $("#row_2").remove();
});

js小提琴示例

如果无法删除行,则可以按可见行和不可见行筛选行:

$("#row_2").fadeOut(function () {
    $('tr:visible').filter(":odd").css('background', '#fff');
});

这是因为您实际上并没有删除该行,而只是隐藏了它。

如果您希望更新样式,则需要在fadeOut()完成后实际从 DOM 中删除该行。

根据你实际对隐藏行做什么,从 DOM 中删除它可能不是一种选择 - 例如,如果您想稍后再次切换它。

如果是这种情况,另一种解决方案可能是插入一个额外的隐藏行。这会将其放回奇数/偶数同步,而不会删除您隐藏的行。然后,您可以在重新显示隐藏行时再次删除多余的行。

如果你想为

前端用户保留淡入淡出的优雅,然后顺利地删除它,当然你可以像这样将淡出与回调删除链接在一起:

<table class="myTable">
    <tr>
        <td>
            Bla bla :) I'm so striped <removebutton>Remove this row</removebutton>
        </td>
    </tr>
    <tr>
        <td>
            Bla bla :) I'm so striped  <removebutton>Remove this row</removebutton>
        </td>
    </tr>
    <tr>
        <td>
            Bla bla :) I'm so striped  <removebutton>Remove this row</removebutton>
        </td>
    </tr>
</table>
<script>
    jQuery('.myTable tr td removebutton').on('click', function() {
        jQuery(this).parent().parent().fadeOut(function() { 
            jQuery(this).remove();
       });
    });
</script>
<style>
    .myTable tr:nth-child(odd) {
        background-color: #EEEEEE; 
    }
</style>