我需要将表格设置为斑马样式,甚至还要对表格的行进行样式设置,我使用了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>
如何动态更改表格的样式?当前结果:
预期结果:
最佳答案
当您隐藏元素时,它仍然存在(只是隐藏),所以这就是您有此问题的原因。
建议您针对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/