我正在尝试替换表格行的背景颜色,每个部分以相同的颜色开头。我用以下代码实现了这个目标:
$(document).ready(function(){ $("tbody tr.row:nth-child(even)").css("background", "#efefef"); });
我还需要能够限制每个tbody部分内可见的行数(例如5个)。这些需要能够通过带有.click()事件的按钮切换。有谁知道我怎么能做到这一点?我提出的唯一解决方案导致背景颜色中断。任何帮助将不胜感激!
以下是表结构的示例:
<table>
<tbody>
<tr>
<td>Cell Contents</td>
<td>Cell Contents</td>
</tr>
<tr>
<td>Cell Contents</td>
<td>Cell Contents</td>
</tr>
<tr>
<td>Cell Contents</td>
<td>Cell Contents</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Cell Contents</td>
<td>Cell Contents</td>
</tr>
<tr>
<td>Cell Contents</td>
<td>Cell Contents</td>
</tr>
<tr>
<td>Cell Contents</td>
<td>Cell Contents</td>
</tr>
</tbody>
</table>
答案 0 :(得分:2)
这应该可以解决问题:
$(function() {
$('#showAll').click(function() {
$('table > tbody').each(function() {
$(this).children('tr:gt(4)').toggle();
});
$("tr:visible").filter(':odd').css("background", "#efefef").end()
.filter(':even').css("background", "#ffffff");
}).click();
});
编辑清理代码(灵感来自@ karim79的答案)。
答案 1 :(得分:1)
这样做(测试过):
var rowLimit = 5;
$(document).ready(function() {
$('button').click(function() {
//hide everything after the rowLimit row
$('table > tbody > tr:gt(' + (rowLimit - 1) + ')').toggle();
});
});
密钥位于gt selector
为了防止你的行样式消失,将它们放在CSS类中,然后使用addClass和removeClass来应用它们,请记住,如果它们不在类中,那么它们就不存在了。)
答案 2 :(得分:0)
滚动。将表的高度设置为5行将适合,然后使用css
溢出:滚动; :d