0

I've got a table design I'm using across multiple tables. There will be some color differences, but they are determined based on classes. ex:

<table id="table" class="table1"> and <table id="table" class="table2">

I want to apply javascript striping to odd rows; however, want it to work on all tables with ID table because on some pages there will be multiple tables with the same ID (just different classes).

I've looked at this code,

 $(document).ready(function(){ 
 $("#table tr:odd").addClass("odd");
 }); 

But it appears to only work on the first table and stops after that. I saw a code the other day that worked; however, now I can't seem to find it. Any suggestions on a javascript code that will work across multiple tables, getting the odd rows from each table separately and applying the class to those rows?

If I didn't phrase this correctly, please let me know and I will try to correct. And I'm not using CSS nth-child to do this because the CSS nth-child doesn't work in IE (at least I havent been able to get it to work). I need this site to work even in older browsers, which is why I'm going back to JS. I also need the JS to work in all browsers.

4

5 回答 5

2

如果您使用 ID 选择器#<whatever>,那么它只会返回匹配的第一个元素。您可以使用$("table tr:odd")或提出一个类来分配所有表,表明它应该具有备用行着色,例如$(".table-striped tr:odd")

备择方案

这些示例将适用于多个表并保持着色顺序相同

$('.table-striped').each(function () {
    $('tr:odd', this).addClass('odd');
});

$(".table-striped tr:nth-child(odd)").addClass("odd");
于 2013-07-05T17:41:52.540 回答
2

改变这个: -

$("#table tr:odd").addClass("odd");

$("table tr:odd").addClass("odd");

你也可以试试这个:-

$(document).ready(function() {
    $("table").find("TR:odd").addClass("odd");
});

JS小提琴

在第一个解决方案中,原始选择器将采用页面上 table 中包含的所有 tr 元素的组,然后采用该巨大集合中的每个其他元素。后者首先创建一组所有表,然后创建每个表中的行的子组,然后每隔一个获取每个子组中的行。

于 2013-07-05T17:42:23.407 回答
1

“嗯,你在这种方法中有一个根本缺陷,因为id值在页面上必须是唯一的。所以你真的不应该将id属性作为脚本的常见“事物”。

好消息是您可以跳过使用 ID 并根据标签本身进行操作。. . $("table tr:odd").addClass("odd");将类应用于<table>页面上每个元素的奇数行。

于 2013-07-05T17:43:57.693 回答
1

你把 ID 和 Class 搞混了

<table id="table" class="table1"> 

应该

<table id="table1" class="table"> 

<table id="table" class="table2">

应该

<table id="table2" class="table">

你的 JS 应该是:

 $(document).ready(function(){ 
     $(".table tr:odd").addClass("odd");
 }); 

ID 应该是唯一的并且只应用一次,它用于标识特定元素。因此名称为“ID”。

一个类用于查找多个元素。

于 2013-07-05T17:46:56.820 回答
0

我们可以使用引导程序。将类table-striped添加到表中。

记住一定要包含必要的引导文件。

于 2018-04-10T05:56:20.757 回答