0

我在 include/menu.php 中有这段代码

<div class="collapse navbar-collapse navbar-ex1-collapse">
      <ul class="nav navbar-nav side-nav">
         <li><a href="registrar_tiempo_carrera.php"><i class="glyphicon glyphicon-paperclip"></i> Registra tus tiempos de Competencias</a></li>
         <li><a href="ver_tiempo_carrera.php"><i class="glyphicon glyphicon-list-alt"></i> Ver tus Marcas de Carreras</a></li>
         <li><a href="agregar_amigos.php"><i class="glyphicon glyphicon-user"></i> Agrega tus Amigos</a></li>
         <li><a href="ranking.php"><i class="glyphicon glyphicon-globe"></i> Rankings Generales</a></li>
         <li><a href="contacto.php"><i class="glyphicon glyphicon-envelope"></i> Reportar un Problema</a></li>
      </ul>
</div>

在 index.php 中

 <body>
  <?php include ('include/menu.php'); ?>

结果: http: //lazaro.inf.uct.cl/~dacanalesc/registratusmarcas/

并在 menu.js 中动态设置 set li 的方法,但没有任何效果

例子:

$('ul li a').click(function() {
  $('ul li.active').removeClass('active');
  $(this).closest('li').addClass('active');
});

我的问题是:在另一个页面中使用 mi 菜单,并在主页中包含它。需要其他方法将活动类放在 li 上吗?

编辑: Twitter Bootstrap 将活动类添加到 li 第一个答案对我有用。

4

2 回答 2

2

我遇到了同样的问题,所以我编写了这段代码

更好的代码

$(document).ready(function () {
    loc = $(location).attr('href');
    $('ul.nav a').filter(function () {
        return this.href == loc;
    }).closest('li').addClass('active');
});

我先做了这个

$(document).ready(function () {
    loc = $(location).attr('href');
    var n = loc.split("/");
    var n1 = loc.split("/").length;
    var on_page = n[n1 - 1];
    var new_page = on_page.split("?");
    $('ul.nav a').each(function () {
        if ($(this).attr('href') == new_page[0]) {
            $(this).closest('li').addClass('active');
        }
    });
});
于 2013-10-28T01:35:59.137 回答
0

In your code :

$('ul li a').click(function() {
$('ul li.active').removeClass('active');
   $(this).closest('li').addClass('active');

});

"this" refer to the "ul li a" element, not to the li.

Replacing $(this).closest('li') by $(this).parent() should answer your question.

BIG EDIT:

I was wrong:

Your problem is that your navbar li are links (<a href="a url...file.php"\>). You have to store in the php code which li is active. You don't have to use Js.

Javascript is usefull only if you don't load another page (refresh the content of the page with Ajax).

For example, in registrar_tiempo_carrera.php you can set:

$current_nav_li = 0;

and in ver_tiempo_carrera.php you can set:

$current_nav_li = 1;

And where you write the left menu:

if($current_nav_li == 1)
   echo '<li **class="active"**><a href="registrar_tiempo_carrera.php"><i class="glyphicon glyphicon-paperclip"></i> Registra tus tiempos de Competencias</a></li>';
else 
   echo '<li><a href="registrar_tiempo_carrera.php"><i class="glyphicon glyphicon-paperclip"></i> Registra tus tiempos de Competencias</a></li>' 
   ... etc ...
于 2013-10-28T01:01:32.650 回答