这是我导航菜单的布局。它应该完美无缺。但是我想要
<li class="active">
在当前处于活动状态的页面上。我怎样才能做到这一点?
home.php:
<?php include 'includes/navbar.php'; ?>
navbar.php:
<li><a href="?page=home">Home</a></li>
<li><a href="?page=about">About</a></li>
//etc
的index.php:
$page = $_GET['page'];
if (!isset($page)) {
include('home.php.php');
}
if ($page == "home") {
include('home.php.php');
}
if ($page == "about") {
include('about.php');
}
//etc
答案 0 :(得分:5)
你可以为每个链接写一个if语句,但这是一个更整洁的方法。
navbar.php
<?php
// using home as default, and not throwing a notice when $_GET['page'] isn't set
$page = (isset($_GET['page'])? $_GET['page'] : 'home');
// create an array of pages and their titles
$pages = array(
'home' => 'Home',
'about' => 'About',
// etc
);
// output each, checking for which is active
foreach ($pages as $pagestring => $text){
$active = ($pagestring == $page? ' class="active"' : '');
echo '<li' . $active . '><a href="?page=' . $pagestring . '">' . $text . '</a></li>';
}
?>
如果某些网页有下拉列表(问题中未显示),则需要做更多的工作......请注意,这会将<ul>
用$currentpage = (isset($_GET['page'])? $_GET['page'] : 'home');
$pages = array(
'home' => 'Home', // just use a string for a simple link
'about' => 'About',
'cute' => array( // use an array for a dropdown
'text' => 'Cute things',
'children' => array(
'kittens' => 'Kittens',
'puppies' => 'Puppies',
)
),
// etc, you can include children in children too
);
echo createLinksRecursive($pages, $currentpage);
function createLinksRecursive($array, $currentpage){
$return = '<ul>';
foreach ($array as $pagestring => $linkarray){
// we don't want to worry about whether it's a string or array more than once
if (!is_array($linkarray)) $linkarray = array('text' => $linkarray);
// check for active
$active = ($pagestring == $currentpage? ' class="active"' : '');
// add the li and anchor element
$return .= '<li' . $active . '>
<a href="?page=' . $pagestring . '">' . $linkarray['text'] . '</a>';
// add children if there are any using the same function
if (isset($linkarray['children'])){
$return .= createLinksRecursive($linkarray['children'], $currentpage);
}
// close that li
$return .= '</li>';
}
// close the ul and return
$return .= '</ul>';
return $return;
}
包裹起来。似乎在你的navbar.php文件中。
.remove()