【问题标题】:jquery equal to PHP <?=++$r%2?'odd':'even'?> for striped table rows?jquery 等于 PHP <?=++$r%2?'odd':'even'?> 对于条带表行?
【发布时间】:2014-02-10 15:30:40
【问题描述】:

我在 PHP 中这样做:++$r%2?'odd':'even' 以应用条纹行..

<tr class="<?=++$r%2?'odd':'even'?>"><td>...</td></tr>

但是当我通过$.ajax-request 获得记录集时,我会返回如下结果:

$('#table_selected tbody').empty();  //  empty the table
$.ajax({  //  fetch new data and insert into new rows
    ...
    success: function(data){
        $.each(data, function(i, array){
            $('#table_selected tbody').append('<tr><td>'+array['name']+'</td></tr>');
        });
    }
});

我想做的是将odd/even-class 添加到每隔一行的&lt;tr&gt;-元素中 - 就像我在 php 中所做的那样。

在 js/jqyery 中是否有类似的方法来实现这一点?

我阅读了这个答案:How do I add odd/even class only for table rows which haven´t had odd/even class yet?,我认为这是我想要实现的目标的开始,但不确定如何将解决方案应用到我的代码中:

$("table tbody tr:nth-child(odd)").addClass("odd");
$("table tbody tr:nth-child(even)").addClass("even");

【问题讨论】:

  • $("#table_selected tbody tr:nth-child(odd)").addClass("odd"); $("#table_selected tbody tr:nth-child(even)").addClass("even"); 在每个循环之后
  • oddeven 类的用途是什么?如果它是纯粹的样式,那么可能有一个纯 CSS 解决方案,可以消除对 PHP 和 JavaScript 的需求。
  • 只有 CSS 方法可以做到这一点,但它在 IE8 或更低版本中不起作用。例如在 CSS 中放 tr:nth-child(odd) {background-color:#333;}
  • 这纯粹是为了为每一行应用不同的样式..这太容易了,我很尴尬..我想错了方向......谢谢@Arun

标签: javascript jquery arrays tablerow


【解决方案1】:

如果您真的只需要对表格的奇数行/偶数行进行条带化,您能否将其添加到页面的 css 中:

#table_selected tbody tr:nth-child(odd){ background-color: green; }
#table_selected tbody tr:nth-child(even){ background-color: yellow; }

如果您需要课程,正如 Arun P Johny 在 cmets 中建议的那样,您可以像这样更新您的脚本:

$('#table_selected tbody').empty();  //  empty the table
$.ajax({  //  fetch new data and insert into new rows
    ...
    success: function(data){
        $.each(data, function(i, array){
            $('#table_selected tbody').append('<tr><td>'+array['name']+'</td></tr>');
        });

        $("#table_selected tbody tr:nth-child(odd)").addClass("odd");
        $("#table_selected tbody tr:nth-child(even)").addClass("even");
    }
});

或者像这样(更类似于你的php方式):

$('#table_selected tbody').empty();  //  empty the table
$.ajax({  //  fetch new data and insert into new rows
    ...
    success: function(data){
        $.each(data, function(i, array){
            $('#table_selected tbody').append(
                $('<tr><td>' + array['name'] + '</td></tr>')
                    .addClass(i % 2 ? 'odd' : 'even')
            );
        });
    }
});

【讨论】:

  • 您提供的第二个解决方案仅将类添加到 table tbody 本身。但我改用了(i % 2 ? 'odd' : 'even')&lt;tr class="'+(i%2?'even':'odd')+'"&gt;
猜你喜欢
  • 2018-12-04
  • 2022-01-05
  • 2013-08-07
  • 2012-08-20
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
相关资源
最近更新 更多