我试图用一种颜色显示第一行,用另一种颜色显示第二行,但是我的代码用两种颜色显示了两次结果,例如,假设我有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>';
}发布于 2010-05-08 20:50:49
您需要更改每行上的类:
$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++;
}发布于 2010-05-08 20:48:19
你的代码应该是这样的
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>';
}发布于 2010-05-08 21:05:10
下面是一个重复次数最少的解决方案:
$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...
);
}https://stackoverflow.com/questions/2794088
复制相似问题