如何使导航项在选定时处于活动状态


How to make the navigation item to be active on selected?

我已经从所有文件中删除了导航部分,并保留在一个名为nav.php的单独文件中,然后在所需的位置调用它

 include ('includes/nav.php');

nav.php文件的内容如下:

<ul>
       <li<?php if ($thisPage=="http://www.finalyearondesk.com")
            echo " class='"selected'""; ?>>
               <a href="http://www.finalyearondesk.com">Home</a></li>
       <li<?php if ($thisPage=="http://www.finalyearondesk.com/contact.php") 
            echo " class='"selected'""; ?>>
               <a href="http://www.finalyearondesk.com/contact.php">Contact US</a></li>
       <li<?php if ($thisPage=="http://www.finalyearondesk.com/downloads.php") 
            echo " class='"selected'""; ?>>
               <a href="http://www.finalyearondesk.com/downloads.php">Downloads</a></li>
</ul>

但问题是,当我访问该页面时,我无法获得选中的当前项目。我的代码有什么问题?

您没有给$thisPage赋值。在nav.php

中的ul之前添加以下代码
<?php
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') 
                === FALSE ? 'http' : 'https';
$host     = $_SERVER['HTTP_HOST'];
$script   = $_SERVER['SCRIPT_NAME'];
$thisPage = $protocol . '://' . $host . $script;
?>

确保你给$thisPage分配了完整的url,并且应该在

行之前
include ('includes/nav.php');

因为在你的niv.php中你没有分配$thisPage