这是我的一个 PHP 示例。谁能找到更短/更简单的方法来做到这一点?
<? foreach($posts as $post){?>
<div class="<?=($c++%2==1)?‘odd’:NULL?>">
<?=$post?>
</div>
<? }?>
<style>
.odd{background-color:red;}
</style>
其他语言的例子也会很有趣。
从根本上说 - 不。这很容易。您可能会将它改写得更短/更清晰,但想法是一样的。我会这样写:
$c = true; // Let's not forget to initialize our variables, shall we?
foreach($posts as $post)
echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>";
如果您想要更少的内联 PHP,一个很好的方法是通过 JavaScript。
使用 jQuery,它很简单:
<script type="text/javascript">
$('div:odd').css('background-color', 'red');
</script>
使用 CSS3,您可以执行以下操作:
div:nth-child(odd)
{
background-color: red
}
但如果您真的希望您的用户看到颜色,最好不要使用几年...
Smarty 内置:
{section name=rows loop=$data}
<tr class="{cycle values="odd,even"}">
<td>{$data[rows]}</td>
</tr>
{/section}
Django 也是如此:
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
我总是将我的斑马行命名为“row0”和“row1”——这使代码更简单一些。
<?php // you should always use the full opening tag for compatibility
$i = 0;
foreach ($rows as $row) {
echo '<tr class="row' . ($i++ % 2) . '">...</tr>';
}
?>
也许是一个带有静态变量的函数?
<?php
function alternate_row_color($css_class) {
static $show = true;
$show = !$show;
if ($show) {
return $css_class;
} else {
return NULL;
}
}
?>
然后使用它(使用您的示例):
<?php foreach($posts as $post) { ?>
<div class="<?=alternate_row_color('odd')?>">
<?=$post?>
</div>
<?php } ?>
<?php $alt = true; foreach ($posts as $post): $alt = !$alt; ?>
<div<?php echo $alt ? ' class="odd"' : ''; ?>>
<!-- Content -->
</div>
<?php endforeach ?>
将是最简单和最清晰的方法。
只是为了好玩
假设您可以使用 CSS3 选择器,您可以执行类似的操作
<div class="posts">
<? foreach($posts as $post){?>
<div>
<?=$post?>
</div>
<? }?>
</div>
<style>
div.posts div:odd{background-color:red;}
</style>
即使有 CSS2 支持和 mootools(javascript 库),您也可以用这个 javascript 替换样式
<script type="text/javascript">
// obviously this script line should go in a js file in a onload (or onDomReady) function
$$('div.posts div:odd').setStyle('background-color','red');
</script>
如果您除了 php a 它什么都没有,您可以使用数组简化代码
<? $isodd=array('','odd');
$c=0;
foreach($posts as $post){?>
<div class="<?=$isodd[$c++%2]?>">
<?=$post?>
</div>
<? }?>
您可以将逻辑封装如下:
<?php
class ListCycler {
private $cols, $offs, $len;
// expects two or more string parameters
public function __construct() {
$this->offs = -1;
$this->len = func_num_args();
$this->cols = func_get_args();
foreach($this->cols as &$c)
$c = trim(strval($c));
}
// the object auto-increments every time it is read
public function __toString() {
$this->offs = ($this->offs+1) % $this->len;
return $this->cols[ $this->offs ];
}
}
?>
<html>
<head>
<style>
ul#posts li.odd { background-color:red; }
ul#posts li.even { background-color:white; }
</style>
</head>
<body>
<div>
<h3>Posts:</h3>
<ul id="posts"><?php
$rc = new ListCycler('odd','even');
foreach($posts as $p)
echo "<li class='$rc'>$p</li>";
?></ul>
</div>
</body>
</html>
它已经足够短了,但我可能会将它包装成一些具有明确名称的辅助函数。这样一来,发生的事情就更明显了,您不必在需要它的所有模板中重复该逻辑。
另一方面,要在两个值a和b之间交替,在循环中执行此操作的好方法是:
x = a;
while ( true ) {
x = a + b - x;
}
您也可以在不加减法的情况下执行此操作:
x = a ^ b ^ x;
其中^是 XOR 运算。
如果你只想在 0 和 1 之间交替,你可以这样做:
x = 0;
while ( true ) {
x = !x;
}
您当然可以使用x作为颜色、CSS 样式类等的索引。
function row_color($cnt,$even,$odd) {
echo ($cnt%2) ? "<tr bgcolor=\"$odd\">" : "<tr bgcolor=\"$even\">";
}
如何使用:
$cnt=0;
while ($row = mysql_fetch_array ($result)) {
row_color($cnt++,"e0e0e0","FFFFFF");
}
您可以滥用 $GLOBAL 范围来存储当前选定的类状态,请参见下面的 table_row_toggle() 函数。是的,我知道滥用 $GLOBAL 范围很脏,但是,嘿,我们是来解决问题的,不是吗?:)
在 HTML 中调用表格行切换功能:
<tr <? table_row_toggle(); ?>>
PHP中的函数:
/* function to toggle row colors in tables */
function table_row_toggle() {
/* check if $trclass is defined in caller */
if(array_key_exists('trclass', $GLOBALS)) {
$trclass = $GLOBALS['trclass'];
}
/* toggle between row1 and row2 */
if(!isset($trclass) || $trclass == 'row2') {
$trclass = 'row1';
} else {
$trclass = 'row2';
}
/* set $trclass in caller */
$GLOBALS['trclass'] = $trclass;
/* write the desired class to the caller */
echo ' class="' . $trclass . '"';
}
<?php ($i%2==1) ? $bgc='#999999' : $bgc='#FFFFFF'; ?>
'<div bgcolor=" bgcolor='.$bgc.'">';
在 Vilx 上找到,但总是尽量减少速度(页面重量)
<tr class="'.(($c = !$c)?'odd':'even').'">
一直在使用这样的东西:
<?php
function cycle(&$arr) {
$arr[] = array_shift($arr);
return end($arr);
}
$oddEven = array('odd', 'even');
echo cycle($oddEven)."\n";
echo cycle($oddEven)."\n";
echo cycle($oddEven)."\n";
一个简单的小功能,对我很有效。
<?php
class alternating_rows()
{
private $cycler = true;
//------------------------------------------------------------------------------
function rowclass($row0,$row1)
{
$this->cycler = !$this->cycler;//toggle the cycler
$class=($this->cycler)?$row0:$row1;
return $class;
}// end function rowclass
//------------------------------------------------------------------------------
}//end class alternating rows
?>
<?php $tablerows= new alternating_rows();?>
<table>
<tr>
<th scope="col">Heading 1</th>
<th scope="col">Heading 2</th>
</tr>
<?php foreach ($dataset as $row){?>
<tr class="<?php echo $tablerows->rowclass("oddrow","evenrow"); ?>">
<td>some data</td>
<td>some more data</td>
</tr>
<?php } //end foreach?>
</table>
在 PHP 中,我使用以下代码:
function alternate($sEven = "even", $sOdd = "odd")
{
static $iCount;
return ($iCount++ & 1) ? $sOdd :$sEven;
}
for($i = 0; $i< 5; $i++)
echo alternate();
/*output:
even
odd
even
odd
even
*/
资料来源:http ://sklueh.de/2013/11/einfache-alternierung-mit-php/