我正在尝试以一种颜色显示第一行,而另一种颜色显示第二行,但我的代码在两种颜色中显示结果两次,例如,假设我有5个结果,我的代码将通过显示10个结果将结果加倍。我该如何解决这个问题?
这是php代码。
while ($row = mysqli_fetch_assoc($dbc)) {
//first row
echo '<h3 class="title"><a href="#" title="">' . $row['title'] .'</a></h3>';
echo '<div class="summary"><a href="#" title="">' . substr($row['content'],0,255) . '</a></div>';
//second row
echo '<h3 class="title-2"><a href="#" title="">' . $row['title'] .'</a></h3>';
echo '<div class="summary-2"><a href="#" title="">' . substr($row['content'],0,255) . '</a></div>';
}
答案 0 :(得分:4)
您需要更改每一行的类:
$count = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
if( $count % 2 == 0 ) {
$classMod = '';
} else {
$classMod = '-2';
}
//first row
echo '<h3 class="title' . $classMod . '"><a href="#" title="">' . $row['title'] .'</a></h3>';
echo '<div class="summary' . $classMod . '"><a href="#" title="">' . substr($row['content'],0,255) . '</a></div>';
$count++;
}
答案 1 :(得分:2)
你的代码应该是这样的
CSS
.odd { background: #CCC }
.event { background: #666 }
PHP
$c = true;
while ($row = mysqli_fetch_assoc($dbc)) {
$style = (($c = !$c)?' odd':' even');
echo '<h3 class="title '.$style.'"><a href="#" title="">' . $row['title'] .'</a></h3>';
echo '<div class="summary '.$style.'"><a href="#" title="">' .substr($row['content'],0,255) . '</a></div>';
}
答案 2 :(得分:1)
这是一个重复性最小的解决方案:
$count = 0;
while (($row = mysqli_fetch_assoc($dbc)) && ++$count) {
printf(
'<h3 class="title%1$s"><a href="#" title="">%2$s</a></h3>'
. '<div class="summary%1$s"><a href="#" title="">%3$s</a></div>'
, $count % 2 ? "" : "-2"
, $row['title'] // might want to use htmlentities() here...
, substr($row['content'], 0, 255) // and here...
);
}
答案 3 :(得分:0)
您的代码只显示两次结果。使用条件(例如整数或布尔值)在行之间切换(如:如果为true,则为绿色;如果为false,则为红色)。
对于布尔值,您可以像这样更改当前值:
bool = !bool;
答案 4 :(得分:0)
$i = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
$color =$i % 2;
echo '<h3 class="title-' .$color . '"><a href="#" title="">' . $row['title'] .'</a></h3>';
echo '<div class="summary"><a href="#" title="">' . substr($row['content'],0,255) . '</a></div>';
$i++;
}
答案 5 :(得分:0)
一些额外的观点:
<div class="stripe">
作为容器,则可以使用例如CSS中的.stripe h3
。 .stripe h3
定位CSS中的奇数项和偶数项,则可以只覆盖奇数项。div:odd
以定位父母的任何奇数子项。这可能需要稍微更改HTML的结构。对于IE7及以下版本,我将使用JavaScript而不是PHP添加类。当IE7不再存在时,你可以删除JS。答案 6 :(得分:0)
顺便说一下,你也可以这样做:
while ($row = mysqli_fetch_assoc($dbc)) {
echo '<h3 class="title"><a href="#" title="">' . $row['title'] .'</a></h3>';
echo '<div class="summary"><a href="#" title="">' . substr($row['content'],0,255) . '</a></div>';
if($row = mysqli_fetch_assoc($dbc)){
echo '<h3 class="title-2"><a href="#" title="">' . $row['title'] .'</a></h3>';
echo '<div class="summary-2"><a href="#" title="">' . substr($row['content'],0,255) . '</a></div>';
}
}
答案 7 :(得分:-1)
IMO,没有理由不将这种非关键的表示层装饰委托给客户端代码。
只需使用像jQuery这样的库,并像这样访问奇数和偶数行:
<script>
$(document).ready(function()
{
//for your table rows
$("tr:even").css("background-color", "#F4F4F0");
$("tr:odd").css("background-color", "#EFF1F2");
});
</script>
接下来我们会让我们生成字体标记。