隐藏行时更新奇数/偶数行颜色 [英] Update odd/even row colors when hiding rows
问题描述
我在一个网页上有几个表格,并且有一个复选框根据其中一个单元格的内容显示/隐藏行。当所有行都可见时,一切都是完美的,行的颜色根据需要交替。当我隐藏行,交替的行颜色不再是正确的(显然)。当复选框被选中时,如何轻松地更新类以保持交替的行颜色,然后在取消选中复选框后恢复正常?
I have several tables on a page and a checkbox to show/hide rows based on the contents of one of the cells. While all rows are visible, everything is perfect and the row colors alternate as needed. When I hide rows though, the alternating row colors are no longer correct (obviously). How can I easily update the classes to keep the alternating row colors when the checkbox is checked and then go back to normal after unchecking the checkbox?
<table id='27249'><thead><tr><th>h1</th><th>h2</th><th>h3</th><th>h4</th><th>h5</th><th>h6</th></tr><thead><tbody>
<tr class='odd'><td>text</td><td>text</td><td>text</td><td>$0.25 </td><td></td><td></td></tr>
<tr class='even'><td>text</td><td>text</td><td>text</td><td>$0.25 </td><td></td><td></td></tr>
<tr class='odd'><td>text</td><td>text</td><td>text</td><td>$0.25 </td><td></td><td></td></tr>
<tr class='even'><td>text</td><td>text</td><td>text</td><td>$0.25 </td><td></td><td></td></tr>
</tbody></table>
Jsfiddle示例 - http://jsfiddle.net/6bfjw/3/
Jsfiddle example - http://jsfiddle.net/6bfjw/3/
推荐答案
几乎没有办法考虑。因为你的用例,纯CSS方法更理论,但实际上不会为你工作。
There are a few approaches to consider. Because of your use-case, the pure css approach is more theoretical, but won't actually work for you.
在一个完美的世界。
In a perfect world...
首先,为了保持你的标记与样式松散耦合,并且允许简单的扩展,支持更灵活的CSS规则。有通常不需要硬编码元素上的甚至
和 odd
这意味着你必须添加这些类,每次你尝试和添加一个新的元素。而是使用css3 :nth-child
选择器:
Firstly, to keep your markup loosely coupled with styling, and allow easy extensibility, favor more flexible CSS rules. There's usually no need to hard-code the even
and odd
classes on elements; that means that you'll have to add those classes every time you try and add a new element. Instead, use the css3 :nth-child
selector:
tbody tr:nth-child(odd) {
background-color:#99FFFF;
}
tbody tr:nth-child(even) {
background-color:#FFFF99;
}
您需要使用JavaScript并手动管理这些类。每次复选框值更改时,将偶数和奇数类重新分配到可见行:
You'll need to use JavaScript, and manually manage these classes. Every time the checkbox value changes, reassign the even and odd classes to the visible rows:
$("#checkbox").change(function () {
if ($("#checkbox").is(":checked")) {
$("table tbody tr").each(function () {
var cell = $.trim($(this).find("td:eq(4)").text());
if (cell.length == 0) {
console.log("empty");
$(this).hide();
}
});
} else {
$("table tbody tr").show();
}
$("table tbody tr").removeClass("odd even");
$("table tbody tr:visible:odd").addClass("odd");
$("table tbody tr:visible:even").addClass("even");
});
(当然这意味着你的CSS保持原来的样子)。
(Of course this means your CSS remains as it was originally).
查看选择器上的 jQuery文档。一些方便的选项是 :even
选择器,以及更详细的 :nth-child
。
Take a look at the jQuery docs on selectors. Some convenient ones are the :even
selector, and the more verbose :nth-child
.
这篇关于隐藏行时更新奇数/偶数行颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!