这可能非常简单,但我正在尝试找出一种方法来将一个类添加到无序列表,然后在每第三个元素之后替换该类..
我只设法在每三个元素上添加一个类(这不是我想要的),但这是我的代码:
<?php $i=1; foreach($this->items as $item) : ?>
<li class="<?php if ($i % 3 == 0) : ?>odd<?php endif; ?>"><a href="<?php echo $linky; ?>">xxx</a></li>
<?php $i++; endforeach; ?>
吐出:
<li class="">xxx</li>
<li class="">xxx</li>
<li class="odd">xxx</li>
<li class="">xxx</li>
<li class="">xxx</li>
<li class="odd">xxx</li>
但我希望得到的是:
<li class="odd">xxx</li>
<li class="odd">xxx</li>
<li class="odd">xxx</li>
<li class="even">xxx</li>
<li class="even">xxx</li>
<li class="even">xxx</li>
等等.. 通常我会使用 jquery 来做这样的事情,但在这种情况下我必须使用 php.. 任何帮助将不胜感激:)
最佳答案
使用 bool 标志,每次 $i % 3 == 0
时都会翻转(取反):
// Start with 0 instead of 1
$i=0;
// Flag starts TRUE
$state = TRUE;
foreach ($this->items as $item) {
if ($i % 3 === 0) {
// Flip to opposite state
$state = !$state;
}
?>
<li class="<?php if ($state) : ?>odd<?php else: ?>even<?php endif; ?>"><a href="<?php echo $linky; ?>">xxx</a></li>
<?php
$i++;
}
Here is a demonstration .尽管您需要检查输出以查看类更改。
关于php - 使用 php 将类添加到 li 然后在每第三个元素之后交替?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11254731/