[英]What's wrong with this ternary operator?
我使用這樣的分頁系統:
<?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;
}
?>
我想將css class="active"
設置為我所在頁面的菜單項。
如果我打印<li>
像這樣的項目,它將起作用:
<li><a href="?p=start" <?php if ($currentPageId == 1) {echo "class='active'";}else {} ?>>Start</a></li>
但是我想改用三元運算符。 我嘗試了這段代碼,但沒有用:
<li><a href="?p=start" <?php ($currentPageId == '1') ? 'class="active"' : '' ?>>Startsida</a></li>
知道為什么嗎?
編輯所以問題是我錯過了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>";
我需要執行此操作,因為我將基於if
語句顯示鏈接。“如果用戶是管理員,則顯示此鏈接,否則不顯示” ...有人解決方案嗎?
您缺少回聲:
<li><a href="?p=start" <?php echo (($currentPageId == '1') ? 'class="active"' : '') ?>>Startsida</a></li>
這應該夠了吧。
解決第二個問題:
<?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>";
}
?>
正如其他人指出的那樣,您缺少回聲。 我還想指出,在這種情況下,您甚至不需要三元運算符,因為在其他情況下,您什么也不做:
<li><a href="?p=start" <?php if ($currentPageId == '1') echo 'class="active"'; ?>>Startsida</a></li>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.