Setting an active class on a menu item with php(使用 php 在菜单项上设置活动类)
问题描述
我有一个由  元素和一个 class="active" 元素组成的简单菜单,用于标记当前页面.$_get[] 传递一个变量,通过 url 选择特定页面:?pg=PAGE.
I have a simple menu made of <ul><li> elements and a class="active" in place to mark the current page. A variable is passed by $_get[] to select the specific page by url: ?pg=PAGE.
我对 php 还很陌生,还在学习中.这工作得很好,但我觉得应该有一种更简单、更短的方法.
I am fairly new to php and still learning. This works just fine, but i feel there ought to be a simpler and shorter way.
<ul class="nav">
  <li <?php if ($_GET['pg'] == "PAGE1") { echo "class="active""; } ?>><a href="?pg=PAGE1">FIRST PAGE</a></li>
  <li <?php if ($_GET['pg'] == "PAGE2") { echo "class="active""; } ?>><a href="?pg=PAGE2">SECOND PAGE</a></li>
</ul>
推荐答案
<?php
    $pages = array(
        'PAGE1' => 'FIRST PAGE',
        'PAGE2' => 'SECOND PAGE');
?>
<ul class="nav">
  <?php foreach ($pages as $pageId => $pageTitle): ?>
  <li <?=(($_GET['pg'] == $pageId) ? 'class="active"' : '')?>><a href="?pg=<?=$pageId?>"><?=$pageTitle?></a></li>
  <?php endforeach; ?>
</ul>
http://php.net/manual/en/control-structures.foreach.php
不要重复自己——两个 li-s 非常相似,唯一的区别是页面 ID 和标题.一旦您拥有两个以上的页面,这种方法将非常有用.
Don't repeat yourself -- both li-s are very similar, the only difference is in page ID and title. This approach will really help once you have more than two pages.
尽量将 PHP 和 HTML 分开——一旦您决定将它们保存在单独的文件中(有时您会这样做),这将使您的生活更轻松.
Try to keep PHP and HTML as separate as possible -- this will make your life easier once you decide to keep them in separate files (and you will sometimes).
这篇关于使用 php 在菜单项上设置活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 php 在菜单项上设置活动类
				
        
 
            
        - Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
 - 覆盖 Magento 社区模块控制器的问题 2022-01-01
 - PHP - if 语句中的倒序 2021-01-01
 - 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
 - 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
 - 如何在 Symfony2 中正确使用 webSockets 2021-01-01
 - 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
 - openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
 - Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
 - PHP foreach() 与数组中的数组? 2022-01-01
 
