PHP navigation menu and active page styling

荒凉一梦 提交于 2019-12-24 13:26:00

问题


Hi I'm trying to generate my websites navigation/page buttons and give the active page a style element. What I have at the moment is applying the style element to the home page but when navigating to other pages the style element stays on the 'Home' button rather than applying itself to the current page.

My pages are dynamic with the url being like so: http://www.website.com/?p=contact

<?php

    $current = array(
        "" => "Home",
        "?p=contact" => "Contact Us",
        "?p=about" => "About Us",
        "?p=privacy" => "Privacy Policy"
    );
    foreach( $current as $k => $v ) {
        $active = $_GET['page'] == $k
            ? ' class="current_page_item"'
            : '';
        echo '<li'. $active .'><a href="./'. $k .'">'. $v .'</a></li>';
    }

?>

I've tried a few things but can't seem to get it working correctly, any help would be greatly appreciated. Thank you :)


回答1:


The following line is the culprit

$_GET['page'] == $k

You should use $_GET['p'] which is your querystring parameter. It will be equal to contact in your example url. So store your array values without the ?p=

<?php

    $current = array(
        "" => "Home",
        "contact" => "Contact Us",
        "about" => "About Us",
        "privacy" => "Privacy Policy"
    );
    foreach( $current as $k => $v ) {
        $active = $_GET['p'] == $k
            ? ' class="current_page_item"'
            : '';
        echo '<li'. $active .'><a href="./'. $k .'">'. $v .'</a></li>';
    }

?>


来源:https://stackoverflow.com/questions/6741977/php-navigation-menu-and-active-page-styling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!