gpt4 book ai didi

PHP 导航栏事件类

转载 作者:行者123 更新时间:2023-12-03 21:50:08 26 4
gpt4 key购买 nike

这是我的导航菜单的布局。它工作得很好,正如它应该的那样。但我想要

 <li class="active">

在当前事件的页面上。我怎样才能实现这一目标?

home.php:

<?php include 'includes/navbar.php'; ?>     

导航栏.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

最佳答案

您可以为每个链接编写一个 if 语句,但这是一种更简洁的方法。

导航栏.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>这似乎不在您的 navbar.php 文件中。

$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;
}

关于PHP 导航栏事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32401467/

26 4 0