php将类添加到活动到下拉菜单

时间:2013-10-09 05:45:25

标签: php if-statement

这是我的代码:当$ thisPage在该页面上时,我将第一个和最后一个“li”工作,它将该类添加为活动状态。但对于下拉菜单,我有点迷失。我尝试了一系列的页面和其他一些东西,但没有运气。

<ul class="nav sf-menu">
    <li><a href="index.php" <?php if ($thisPage == 'index'){?> class="active"<?php }?>>Home</a></li>
    <li class="sub-menu"><a href="javascript:{}">About</a>          
      <ul>
        <li><a href="team.php"><span>--</span> The Team</a></li>
        <li><a href="about.php"><span>--</span> About</a></li>
        <li><a href="services.php"><span>--</span> Services</a></li>
        <li><a href="testimonials.php"><span>--</span> Testimonials</a></li>
        <li><a href="timeline.php"><span>--</span> Timeline</a></li>
      </ul>
    </li>
    <li><a href="gallery.php" <?php if ($thisPage == 'gallery'){?> class="active"<?php }?>>Gallery</a></li>
</ul>

2 个答案:

答案 0 :(得分:2)

您可以使用多个OR条件:

<li class="sub-menu"><a <?php echo ($thisPage == 'team' || $thisPage == 'about' || $thisPage == 'services' || $thisPage == 'testimonials' || $thisPage == 'timeline') ? 'class="active"' : ''?> href="javascript:{}">About</a>

或者最好是数组:

<?php $aboutPages = array('team','about','services','testimonials','timeline'); ?>
<li class="sub-menu"><a <?php echo in_array($thisPage,$aboutPages) ? 'class="active"' : ''?> href="javascript:{}">About</a>    

答案 1 :(得分:0)

数组可能就是你应该去的地方。使用多维数组并迭代,见下文。递归地使用函数允许更少/更强健的代码。这适用于您的菜单以及包含许多子级别的菜单。

$menu = array(
    'index'=>'Home',
    'about'=>array(
        'team'=>'The Team',
        'about'=>'About',
        'services'=>'Services',
        'testimonials'=>'Testimonials',
        'timeline'=>'Timeline'
    ),
    'gallery'=>'Gallery'
);

function create_menu($menu,$thisPage)
{
    $i = 1;
    foreach ($menu as $page=>$title)
    {
        if (is_array($title))
        {
            echo '<ul>';
            create_menu($title);
        }
        else
        {
            $active    = ($thisPage == $page) ? "active":"";
            echo  "<li><a class=\"$active\" href=\"{$page}.php\"><span>--</span> {$title}</a></li>";
            echo (count($menu) == $i) ? "</ul>":"";

            $i++;
        }
    }
}

// ehco'ing out in this example, but probably better to store in a variable before echoing
echo '<ul>';
create_menu($menu,'index'); // here you pass in $thisPage like so create_menu($menu,$thisPage);
echo '</ul>';