我有一个网站,其中导航栏是完全动态的,您可以根据需要添加多个孩子!逻辑很好,但我只需要添加一个分隔符,根据设计要求将它们彼此分开。现在问题是...... <li class="divider"></li>
有效,但它也将分隔符添加到导航栏菜单的每次迭代的最后一个索引,因为它是自解释的。我不想在循环的最后一次迭代中添加一个分隔符!
这是我的代码:
<ul class='nav navbar-nav'>
<li><a href="index.php" style="color: white;"><img id="navbar-home" src="images/navbar_home.png" class="img-responsive"></a></li>
<?php
function display_children($parent, $level) {
$conn=mysqli_connect("localhost","root","") or die ("not connected");
mysqli_select_db($conn,"occ")or die ("not selected");
$result = mysqli_query($conn,"SELECT a.id, a.title,a.page_id, Deriv1.Count FROM `menu` a LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `menu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent=" . $parent);
while ($row = mysqli_fetch_array($result)) {
if ($row['Count'] > 0) {
echo "<li><a href='" . base_url().'pages/'.$row['page_id'] . "'>" . strtoupper(str_replace('-', ' ', clean($row['title']) )). "<span class=caret></span></a>";
echo "<ul class=\"dropdown-menu\">";
display_children($row['id'], $level + 1);
echo "</ul>";
echo "</li>";
echo "<li class=\"divider\"></li>";
} elseif ($row['Count']==0) {
echo "<li><a href='" . base_url().'pages/'.$row['page_id'] . "'>" . strtoupper(str_replace('-', ' ', clean($row['title'])) ) . "</a></li>";
echo "<li class=\"divider\"></li>";
} else;
}
}
function clean($string) {
return preg_replace('/[^A-Za-z0-9\-]/', ' ', $string); // Removes special chars.
}
display_children(0, 1);
?>
</ul>
以下是该问题的屏幕截图,以防有人想澄清:
答案 0 :(得分:2)
您可以使用纯CSS执行此操作,使用last-child选择器:
.nav .dropdown-menu .divider:last-child {
display: none;
}
要使用php,您可以代替回显所有菜单项,将其添加到数组中,并检查最后一项是否等于分隔符。然后你的代码看起来像这样:
function display_children($parent, $level) {
$conn=mysqli_connect("localhost","root","") or die ("not connected");
mysqli_select_db($conn,"occ")or die ("not selected");
$result = mysqli_query($conn,"SELECT a.id, a.title,a.page_id, Deriv1.Count FROM `menu` a LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `menu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent=" . $parent);
$returnHtml = array();
while ($row = mysqli_fetch_array($result)) {
if ($row['Count'] > 0) {
$returnHtml[] = "<li><a href='" . base_url().'pages/'.$row['page_id'] . "'>" . strtoupper(str_replace('-', ' ', clean($row['title']) )). "<span class=caret></span></a>";
$returnHtml[] = "<ul class=\"dropdown-menu\">";
display_children($row['id'], $level + 1);
$returnHtml[] = "</ul>";
$returnHtml[] = "</li>";
$returnHtml[] = "<li class=\"divider\"></li>";
} elseif ($row['Count']==0) {
$returnHtml[] = "<li><a href='" . base_url().'pages/'.$row['page_id'] . "'>" . strtoupper(str_replace('-', ' ', clean($row['title'])) ) . "</a></li>";
$returnHtml[] = "<li class=\"divider\"></li>";
} else;
}
if (end($returnHtml === "<li class=\"divider\"></li>")) {
array_pop($returnHtml);
}
return implode('', $returnHtml);
}
function clean($string) {
return preg_replace('/[^A-Za-z0-9\-]/', ' ', $string); // Removes special chars.
}
echo display_children(0, 1);