我想使用PHP
及其foreach
循环生成导航菜单。因此,由于"家庭"项目与其他项目有所不同,因此我想称呼他,并在某种情况下改变其风格。此代码以外的所有其他菜单项都可以正常工作,因为它出于某种原因将array
添加到<li>
标签中。你能告诉我我在这里犯的错误吗?
<?php
$menu = array("Home" => "http://mywebsite.com", "Projects" => "/projects/", "About" => "/about/", "Contact" => "/contact/");
foreach ($menu as $opis => $link)
{
if (strtolower($opis) == $_GET['go'])
{
$style = "class="active"";
}
else
{
if (!$_GET['go'] || $_GET['go'] == "home")
{
$style[0] = "class="active"";
echo $style[0] . " ";
}
}
echo "<li ".$style."><a href=".$link.">".$opis."</a></li>";
}
?>
您需要将$style
设置为''
。如果您不这样做,一旦设置,您将在下一个迭代中保持class="active"
。
$menu = array("Home" => "http://mywebsite.com", "Projects" => "/projects/",
"About" => "/about/", "Contact" => "/contact/");
if(empty($_GET['go'])) $_GET['go'] = 'home';
foreach ($menu as $opis => $link)
{
$style = (strtolower($opis) == $_GET['go']) ? "class="active"" : '';
echo "<li $style><a href='$link'>$opis</a></li>n";
}
这是因为当$GET['go']
为home
-
$style[0] = "class="active"";
将其更改为$style = "class="active"";