... 但是当我通过 $.ajax 获取记录集时-请求,我返回的结果是这样的: $('#table_selec-6ren">
gpt4 book ai didi

javascript - jquery 等于 PHP 对于 strip 表行?

转载 作者:行者123 更新时间:2023-12-02 17:46:51 24 4
gpt4 key购买 nike

我在 PHP 中执行此操作:++$r%2?'odd':'even'为了应用条纹行..

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

但是当我通过 $.ajax 获取记录集时-请求,我返回的结果是这样的:

$('#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 -类到<tr> -每隔一行的元素 - 就像我在 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");

最佳答案

如果您确实只需要对表奇数/偶数行进行 strip 化,您是否可以将其添加到页面的 css 中:

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

如果您需要这些类(class),正如 Arun P Johny 在评论中建议的那样,您可以像这样更新脚本:

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

关于javascript - jquery 等于 PHP <?=++$r%2 ?'odd' :'even' ?> 对于 strip 表行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com