用户单击并在新页面中打开时,子菜单保持活动状态

时间:2014-12-16 16:05:30

标签: javascript php css menu

当访问者点击子菜单并且链接在新页面中打开时,我遇到问题,因此我希望该子菜单在该页面上保持活动状态。

我有css类活动和javascript打开它,我需要的是使用php来激活它。 这是UL的课程:

这是我的代码。可以用php或javascript完成。

<ul>
<?php 
$qKategori = ("SELECT * FROM kategori WHERE kprind = 0");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {

while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){ 
$emrikategorise = $exKat['kemri'];
$idkategori = $exKat['kid'];
$idprind = $exKat['kprind'];
?>  

<li><a href="#"><?=$emrikategorise;?></a>

<ul>
<?php 
$qPrind = ("SELECT * FROM kategori WHERE kprind = '".$idkategori."'");              
$rPrind = mysqli_query($dbc,$qPrind);

while($prind = mysqli_fetch_array($rPrind)) {                 
?>
<li><a href="kategori.php?kid=<?=$prind['kid']?>"><?=$prind['kemri']?></a>   </li>
<?php 
}
mysqli_free_result($rPrind);    
?>
</ul>

</li>

<?php                   }       
mysqli_free_result($rKategori); 
}   

?>
</ul>

您可以在左侧看到菜单。网站是www.sitimobil.mk

1 个答案:

答案 0 :(得分:0)

您可能需要在输出之前构建数组,以便能够确定哪些菜单应该处于活动状态。您还可以将其与查询优化结合使用,而不必为每个类别执行1次查询。

类似的东西:

$active = isset($_GET['kid'] ? $_GET['kid'] : -1;
$tree = array();
$list = array();
$qKategori = ("SELECT * FROM kategori ORDER BY kprind");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
   while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){ 
      $id = $exKat['kid'];
      //To prevent numerical array with unused space
      $name = 'kategori'.$exKat['kid']; 
      $list[$name] = $exKat;

      //Calculate depth to see if the menu is a sub..sub..sub menu etc.
      $parent = $list[$name]['kprind'];
      if($parent == 0) {
         $list[$name]['depth'] = 0;
         $list[$name]['childCount'] = 0;
      }
      else {
         $list['kategori'.$parent]['childCount']++;
         $list[$name]['depth'] = $list['kategori'.$parent]['depth']+1; //Increment
      }

      if($id == $active) {
         $list[$name]['active'] = true;

         while($parent != 0) {
            $parentName = 'kategori'.$parent;
            $list[$parentName]['active'] = true;
            $parent = $list[$parentName]['kprind'];
         }
      }
      else 
         $list[$name]['active'] = false;
   }  
   mysqli_free_result($rPrind); 
   //Once we have that we can output the results...

   function output_menu($list, $parent = 0, $active = false)
       $activeClass = $active ? ' class="active"' : '';
       echo '<ul'.$activeClass.'>';
       foreach($list as $row){
          if($row['kprind'] != $parent) continue;
          $link = $row['kprind'] == 0 ? '#' : 'kategori.php?kid='.$row['kid'];
          echo '<li><a href="'.$link.'">'.$row['kemri'].'</a>';
          if($row['childCount'] > 0) 
           output_menu($list, $row['kprind'], $row['active']);
          echo '</li>';
       }
       echo '</ul>';
   }
   output_menu($list);
}

这仍然有点粗糙,但应该这样做。它可能可以进行优化,这样我们就不必多次遍历列表,但可以不必请求过多的数据库调用。这应该会导致数据库的工作负载更轻,输出速度更快。