JQuery< tr>条纹奇数/偶数行 [英] JQuery <tr> stripe odd/even rows

查看:147
本文介绍了JQuery< tr>条纹奇数/偶数行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速的JQuery问题,我有一个用户可以过滤的产品页面。每次应用/删除过滤器时,更改事件都会调用 stripeTable()。我尝试使用以下函数实现表条带化,但是在删除项目并调用stripTable()之后,条带化不会保持一致,即每个可见的奇数行一种颜色,每个可见甚至是另一种颜色。

quick JQuery question, I've got a products page that the user can filter. Each time a filter is applied/removed, a change event calls stripeTable() . I tried to implement the table striping using the following function, however after removing an item and calling stripTable(), the striping did not remain consistent, i.e each visible odd row one colour, each visible even row another.

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');
    });
}

我无法理解上述原因无效的原因。我设法实现如下的功能,它工作正常。有什么想法?

I cannot work out why the above wouldn't work. I managed to implement the function as below and it works fine. Any ideas?

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()是最后一个调用的函数,表格行被隐藏/显示在表格中。谢谢。

For clarity, stripeTable() is the last function called, the table rows are hidden/shown in the table before hand. Thanks.

推荐答案

psuedo-selectors的顺序很重要。

The order of the psuedo-selectors matters.

// Computes "even" first, then "visible"
"#resultsTable > tbody > tr:even:visible"

// Compute "visible" first, then "even"
"#resultsTable > tbody > tr:visible:even"

示例小提琴

Example Fiddle

这篇关于JQuery< tr>条纹奇数/偶数行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆