doutuo7126 2013-11-03 04:23
浏览 88

如何在PHP中创建活动导航栏?

Hello I'm trying to make my navigation bar active in php, so that user can know in which page they are on. I'm new to php and don't know much about it. So how can I add a class="active" in this code to make a active nav bar and display all the page in same index.php page.

 <a href="?page=home"> Home</a></br>
<a href="?page=news"> News</a></br>
<a href="?page=about"> About</a></br>
<a href="?page=contact"> Contact</a></br>

 <?php
if (!isset($_GET['page'])) {
    include "home.php";
} else {
switch ($_GET['page']) {
    case "home":
         include "home.php";
    break;
    case "news":
         include "news.php";
    break;
    case "about":
         include "about.php";
    break;
    case "contact":
         include "contact.php";
    break;
    default:
         include "home.php";
    };
}
?>
  • 写回答

4条回答 默认 最新

  • dongmi4035 2013-11-03 04:49
    关注

    Create an array of menu items and then use a foreach loop to generate the menu dynamically.

    That way when you add new items to the array they will show up in the menu:

    <html>
    <head>
        <title>Website</title>
    
        <style type="text/css" media="screen">
            .active {
                font-weight: bold;
            }
        </style>
    </head>
    <body>
    
    <?php
    
    // This is your menu
    $items = array("home", "news", "about", "contact");
    
    foreach ($items as $item)
    {
        if (isset($_GET['page']) && $_GET['page'] == $item)
        {
            echo '<a href="?page=' . $item . '" class="active"> ' . $item . '</a></br>';
            $activePage = $item . ".php";
        }
        else
        {
            echo '<a href="?page=' . $item . '"> ' . $item . '</a></br>';
        }
    }
    
    // Include your page
    if (isset($activePage))
    {
        include $activePage;   
    }
    else
    {
        include "home.php";
    }
    
    ?>
    
    </body>
    </html>
    

    You should replace all of your code with this code and give it a spin. Using loops to reduce the amount of redundant markup you need to write is not only DRY but will save you a lot of time in the future!

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据