[英]Easiest way to alternate row colors in PHP/HTML?
这是我的一个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之外什么都没有,你可以使用数组简化一些代码
<? $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>
您可以滥用$ 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').'">
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");
}
虽然它很短,但我可能会把它包装成一个名字明确的辅助函数。 这样就可以更明显地发生了什么,你不必在你需要的所有模板中重复那个逻辑。
在另一方面,要在两个值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样式类等。
在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/
一直在使用这样的东西:
<?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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.