我有一个导航,我根据页面上的变量回显了类。
<ul class="nav">
<li class="<?php echo ($page == 'home' ? 'active' : 'inactive'); ?>" class="nav-active"><a href="/" title="Home Page">Home</a></li>
<li class="<?php echo ($page == 'home' ? 'active' : 'inactive'); ?>" class="nav-active"><a href="/" title="Another Page Page">Another Page</a></li>
</ul>
我是PHP的新手,我正在试图弄清楚我如何将它变成一个函数,所以我可以调用它并添加参数。
<li class="<php activeNav($page, $current); ?>">
有人可以解释一下如何做到这一点吗?抱歉没有给出一个非常具有描述性的标题,不知道该怎么称呼它。
答案 0 :(得分:2)
我不明白为什么这会改善你的代码,但你可以试试这个:
PHP:
function activeNav($page, $current) {
return ($page == $current) ? "active" : "inactive";
}
HTML:
<li class="<?php echo activeNav($page, 'home'); ?>">
答案 1 :(得分:1)
function activeClass( $page, $current = 'index') {
if( $page == $current){
return ' active';
}
return ' inactive';
}
用法:
<ul class="nav">
<li class="nav-active<?php echo activeNav( 'home', $page); ?>"><a href="/" title="Home Page">Home</a></li>
<li class="nav-active<?php echo activeNav( 'another', $page); ?>"><a href="/" title="Another Page Page">Another Page</a></li>
</ul>
function printNavigationElement( $page, $title, $current = 'index'){
$title = htmlspecialchars( $title);
return '<li class="nav-active' . activePage( $page, $current) . '"><a href="/' . htmlspecialchars($page) .
'" title="' . $title . '">' . $title . '</a></li>';
}
用法:
<ul class="nav">
<?php
echo printNavigationElement( 'home', 'Home page', $page);
echo printNavigationElement( 'another', 'Another page', $page);
?>
</ul>
class NavigationItem {
public $url;
public $title;
public function __construct( $url, $title){
$this->url = $url;
$this->title = $title;
}
}
class Navigation {
// You should use setters and getters with protected variables
public $current = '';
public $items = array()
public function display() {
echo '<ul class="nav">';
foreach( $this->items as $item){
printNavigationElement( $item->url, $item->title, $this->current);
}
echo '</ul>'
}
}
用法:
<?php
$navigation = new Navigation();
$navigation->current = $page;
$navigation->items[] = new NavigationItem( 'home', 'Home page');
$navigation->items[] = new NavigationItem( 'another', 'Another page');
$navigation->display();
答案 2 :(得分:0)
假设$page
是当前页面,$current
是您想要检查的页面类型,您可以这样做:
function activeNav($page, $current) {
$class = ($page == $current) ? 'active' : 'inactive';
return $class;
}
<li class="<?php echo activeNav('home', 'home'); ?> nav-active"><a href="/" title="Home Page">Home</a></li>