2011-11-18 115 views
3

我有一个PHP循环,显示我的网站上特定发布的数据。我想要做的是为返回的行数动态地分配一个甚至奇数的CSS类。例如,PHP循环,偶数/奇数行返回

first row returned - odd class 
second row returned - even class 
third row - odd class 

这将允许我分配不同的背景颜色以保持数据在视觉上分离。

我应该澄清一下 - 这个数据并没有在表格中被返回。

while ($row = mysql_fetch_assoc($result)) { 

    echo " 
    <div class=\"songContainer\" id=\"" . $row['trackid'] . "\"> 
+0

你的问题是什么?你试过什么了?请张贴一些代码。请使用网站的搜索功能(因为这看起来像一个重复的问题)。 – hakre

+0

更快地拥有像datatables.com前端jquery代码 - 谷歌“jquery表显示插件”。 –

+1

[php:如何在数组中添加奇数/偶数循环]可能的重复(http://stackoverflow.com/questions/1403213/php-how-to-add-odd-even-loop-in-array) – hakre

回答

12

根据哪些浏览器,你有目标,你可能只是做到这一点与CSS:

.mytable tr:nth-child(even) { background-color: #FFF; } 
.mytable tr:nth-child(odd) { background-color: #EEE; } 

你甚至可以做更复杂的事情与此伪类:http://www.quirksmode.org/css/nthchild.html

如果你真的需要PHP,使用模:

$i = 0; 
foreach ($arr as $val) { 
    if (0 == $i % 2) { 
     // even 
    } 
    else { 
     // odd 
    } 
    $i++; 
} 
2

像这样在CSS3中支持nth-child类。

table tr:nth-child(even) td{ 

} 

table tr:nth-child(odd) td{ 

} 

但是,如果你也要支持较老的,你别无选择,只能通过PHP生成类名。

0

使用此jQuery的:

$("tr:nth-child(2n)").addClass("even") 
    .prev().addClass("odd"); 

它选择每秒tr元素并为其添加一个偶数类。然后它选择以前的tr元素并向它添加一个奇怪的类。

Example

0
$num_rows = 0; 
$current_class = ""; 
while ($row = mysql_fetch_array($result)){ 
    $current_class = "class_odd"; 
    if($num_rows % 2 == 0){ 
     $current_class = "class_even"; 
    } 

    $num_rows++; 
}