快速的 JQuery 问题,我有一个用户可以过滤的产品页面。每次应用/删除过滤器时,更改事件都会调用 stripeTable()
。我尝试使用以下函数实现表条纹,但是在删除元素并调用 stripTable() 后,条纹并没有保持一致,即每个可见的奇数行一种颜色,每个可见的偶数行另一种颜色。
function stripeTable() {
// Find all odd visible table rows and add .odd class.
$("#resultsTable > tbody > tr:even:visible").each(function() {
$(this).addClass('even');
});
// Find all even visible table rows and add .even class.
$("#resultsTable > tbody > tr:odd:visible").each(function() {
$(this).addClass('odd');
});
}
我不明白为什么上面的方法不起作用。我成功地实现了如下功能并且运行良好。有什么想法吗?
function stripeTable() {
var count = 1;
// get all visible table rows
$("#resultsTable > tbody > tr").each(function () {
// If table row is visible, strip accordingly.
// Row 0 (table headers) not striped.
if ($(this).is(":visible") && (this.rowIndex !== 0)) {
if ((count % 2) != 0) {
// Remove class .even if applied previously
$(this).removeClass("even");
// Odd row, add class .odd
$(this).addClass("odd");
count++;
} else {
// Remove class .odd if applied previously
$(this).removeClass("odd");
// Even row, add class .even
$(this).addClass("even");
count++;
}
}
});
}
为了清楚起见,stripeTable()
是最后调用的函数,表格行预先隐藏/显示在表格中。谢谢。
最佳答案
伪选择器的顺序很重要。
// Computes "even" first, then "visible"
"#resultsTable > tbody > tr:even:visible"
// Compute "visible" first, then "even"
"#resultsTable > tbody > tr:visible:even"
<强> Example Fiddle
关于javascript - JQuery <tr> strip 奇数/偶数行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36019387/