【问题标题】:CSS vs jQuery How to create dynamic table style (zebra) without others plugins?CSS vs jQuery 如何在没有其他插件的情况下创建动态表格样式(斑马)?
【发布时间】:2013-01-22 21:50:48
【问题描述】:

我需要将表格样式设置为斑马线,甚至表格行的样式,我使用了 css :nth-of-type(even)。但是例如当我需要隐藏表格的一些程式化元素时,就会丢失。将动态样式创建为桌子的斑马线的最简单方法是什么?

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <style type="text/css">
    table tr:nth-of-type(even){background: yellow;}
  </style>
  <script type="text/javascript">
    function hideRow(){
      $(".hidden").hide();
    }
  </script>
</head>
<body>
<center>
 <table cellspacing="0" border="1">
     <tbody>
    <tr class="table-row">
      <td>row1</td>
    </tr>
    <tr class="table-row">
      <td>row2</td>
    </tr>
    <tr class="table-row hidden">
      <td>row3</td>
    </tr>
    <tr class="table-row">
      <td>row4</td>
    </tr>
    <tr class="table-row">
      <td>row5</td>
    </tr>
    </tbody>
 </table>
 <input type="submit" onclick=" hideRow()" value="submit"/> 
 </center>
</body>
</html>

如何动态改变表格的样式?

当前结果:

预期结果:

【问题讨论】:

标签: javascript jquery css html


【解决方案1】:

当您隐藏元素时,它仍然存在(只是隐藏),这就是您遇到此问题的原因。 我建议您针对 css :nth-of-type(even) 选择器创建简单的脚本。一、两个类:

.table_odd { color: yellow; } 
.table_even {color: white; }

现在克里特函数:

function refrestTableColoring( $tableSelector ) {
    $tableSelector.find('tr:odd:not(.hidden)').removeClass('table_even').addClass('table_odd');
    $tableSelector.find('tr:even:not(.hidden)').removeClass('table_odd').addClass('table_even'); 
}

然后用法很简单。调用文档准备好和隐藏元素时:

refrestTableColoring( $('table') );

【讨论】:

  • 谢谢,这个决定很有帮助,只需对选择器稍作调整:'tr:not(.hidden):odd' 和 'tr:not(.hidden):even'
【解决方案2】:

您可以使用 remove() 而不是 hide()。像这样写:

$('input[type="submit"]').click(function(){
    $(".hidden").remove();
});

查看http://jsfiddle.net/fhbgM/

【讨论】:

  • 当用户重置过滤器时会发生什么?
【解决方案3】:
 table tr[@display=block]:nth-of-type(even){background: yellow;}

这行得通吗?

免责声明:未经测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-28
    • 2012-08-26
    • 2016-11-03
    • 1970-01-01
    • 2017-12-10
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多