php - 使用 php 将类添加到 li 然后在每第三个元素之后交替?

标签 php css addclass

这可能非常简单,但我正在尝试找出一种方法来将一个类添加到无序列表,然后在每第三个元素之后替换该类..

我只设法在每三个元素上添加一个类(这不是我想要的),但这是我的代码:

<?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/

相关文章:

php - 将数据从一个 MYSQL 数据库迁移到另一个

phpMyAdmin 无法导出数据库

javascript - 当光标悬停在图像上时显示文本

html - 简单的响应式设计\最佳实践

javascript - 查找然后替换类和文本到按钮

jquery - 有没有办法用 jQuery 自动在多级列表中添加类?

javascript - 创建一个 javascript 函数来根据单击的列表元素在列表元素之间切换类

php - Magento - 如何在 EE 1.9 中使用 JoinTable 函数

php - 在 jQuery 中调用 ajax 时如何访问 PHP 变量?

css - 将 div 垂直放置在具有固定高度和宽度的父 div 上