javascript - CSS vs jQuery 如何在没有其他插件的情况下创建动态表格样式(斑马)?

标签 javascript jquery css html

我需要将表格设置为斑马样式,甚至表格行的样式,我使用了 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>

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

С当前结果:
enter image description here enter image description here
预期结果:
enter image description here enter image description here

最佳答案

当你隐藏元素时,它仍然存在(只是隐藏),所以这就是你遇到这个问题的原因。 我建议您针对 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') );

关于javascript - CSS vs jQuery 如何在没有其他插件的情况下创建动态表格样式(斑马)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459523/

相关文章:

html - div 和图像的左浮动

javascript - 期望 'this' 被类方法使用

javascript - IE6/7 Google Maps tile transparency - 我看不到 map

JavaScript removeClass 不适用于 bootstrap-select

javascript - jQuery CSS 字体大小

jquery - 页面加载时 bootstrap 4 模态播放 iframe?

javascript - jQuery AJAX 到 Node 服务器抛出 net::ERR_CONNECTION_REFUSED

javascript - 更新 ng 类上的特定对象

javascript - 如何在新的空白页上打印提示框输出结果而不是警告框本身?

javascript - 引用错误 : function is not defined