我使用这样的分页系统:
<?php
$p = $_GET['p'];
switch($p)
{
case "start":
$p = "pages/start.php";
$currentPageId = 1;
break;
case "customers":
$p = "pages/customers.php";
$currentPageId = 2;
break;
default:
$p = "pages/start.php";
$currentPageId = 1;
break;
}
?>
Run Code Online (Sandbox Code Playgroud)
我想将CSS设置class="active"为我所在页面的菜单项.
如果我打印这样的<li>项目它是有效的:
<li><a href="?p=start" <?php if ($currentPageId == 1) {echo "class='active'";}else {} ?>>Start</a></li>
Run Code Online (Sandbox Code Playgroud)
但我想用三元运算符代替.我试过这段代码,但它不起作用:
<li><a href="?p=start" <?php ($currentPageId == '1') ? 'class="active"' : '' ?>>Startsida</a></li>
Run Code Online (Sandbox Code Playgroud)
知道为什么吗?
编辑
所以问题是我错过了echo.现在让我稍微扩展一下这个问题......
我需要将我的整个内容封装<ul>在<?php ?>标签内.所以我想要的是这样的:
echo "<div id='nav'>";
echo "<ul>";
echo "<li><a href='?p=start' /* ternary operator to match if the page I'm on is equal to $currentPageId as defined in the paging system (above), if so set class='active' else do nothing*/>Start</a></li>;
echo "<li><a href='?p=customers' /* ternary operator to match if the page I'm on is equal to $currentPageId as defined in the paging system (above), if so set class='active' else do nothing*/>Customers</a></li>;
echo "</ul>";
echo "</div>";
Run Code Online (Sandbox Code Playgroud)
我需要这样做,因为我将根据if语句显示链接.."如果用户是管理员显示此链接,否则不要"......任何人都有解决方案?
你错过了一个回声:
<li><a href="?p=start" <?php echo (($currentPageId == '1') ? 'class="active"' : '') ?>>Startsida</a></li>
Run Code Online (Sandbox Code Playgroud)
这应该够了吧.
解决第二个问题:
<?php
if($something == true) {
echo "<div id='nav'>"."\n<br>".
"<ul>"."\n<br>".
'<li><a href="?p=start"'. (($currentPageId == '1') ? 'class="active"' : '') .'>Startsida</a></li>'."\n<br>".
'<li><a href="?p=customers" '. (($currentPageId == '1') ? 'class="active"' : '') .' >Customers</a></li>'."\n<br>".
"</ul>"."\n<br>".
"</div>"."\n<br>";
}
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
770 次 |
| 最近记录: |