问题
Instead of repeating the navigation bar code in every page I want to write a single snippet of PHP code for the navigation menu bar and include that file in the relevant pages. My first HTML code of the navigation bar menu is as follows. (By default, "USERS" is selected.)
<ul>
<li class="active" ><a href="administrator1.php"><span><B>USERS</B></span></a></li>
<li><a href="administrator2.php"><span><B>CREATE PROFILE</B></span></a></li>
<li><a href="administrator3.php"><span><B>PAYMENTS</B></span></a></li>
<li><a href="administrator4.php"><span><B>DEFENSE</B></span></a></li>
<li><a href="administrator5.php"><span><B>PROGRESS REPORT</B></span></a></li>
</ul>
So I changed the above code to a PHP Code. The file name having this code is 'test.php'
<?php
$menu = array(
'users' => array('text'=>'USERS', 'url'=>'?p=administrator1.php'),
'createProfile' => array('text'=>'CREATE PROFILE', 'url'=>'?p=administrator2.php'),
'payment' => array('text'=>'PAYMENTS', 'url'=>'?p=administrator3.php'),
'defense' => array('text'=>'DEFENSE', 'url'=>'?p=administrator4.php'),
'progressReport' => array('text'=>'PROGRESS REPORT', 'url'=>'p=administrator5.php'),);
class Nav {
public static function GenerateMenu($items) {
$html = "<ul>";
foreach($items as $item) {
$html .= "<li><a href='{$item['url']}' ><span><B>{$item['text']}</B></span> </a></li>";
}
$html .= "</ul>";
return $html;
}
};
?>
In 'administrator1.php' i called the above function as follows;
<?php
include 'test.php';
echo Nav::GenerateMenu($menu);
?>
My problem is, how can I put 'administrator1.php' as the by default selected menu list item and how to put the selected list item a CSS class?
The selected list item should have 'active' CSS class.
<li class="active" >
回答1:
Check if the current script file name is part of the url that is being displayed in the navigation. If so, then assign active
class to it.
foreach($items as $item) {
if(stristr($item['url'],__FILE__)===FALSE)
{
$html .= "<li><a href='{$item['url']}' ><span><B>{$item['text']}</B></span> </a></li>";
}
else
{
$html .= "<li class='active'><a href='{$item['url']}' ><span><B>{$item['text']}</B></span> </a></li>";
}
}
来源:https://stackoverflow.com/questions/19463730/global-navigation-with-active-selector-php