twitter-bootstrap 使用引导程序设置我的导航栏链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16856287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 17:15:38  来源:igfitidea点击:

Set link of my navbar active with bootstrap

javascriptjqueryhtmltwitter-bootstrapnavbar

提问by mpgn

I try to set active the element of my navbar when I click on the button.

当我单击按钮时,我尝试将导航栏的元素设置为活动状态。

My navbar is like that:

我的导航栏是这样的:

navbar

导航栏

But when I click on the "a" for exemple, the "G" remains active.

但是,例如,当我单击“a”时,“G”仍处于活动状态。

My code is like that:

我的代码是这样的:

<div class="navbar span8" id="navbar">
    <div class="navbar-inner">
        <ul class="nav">
             <li><a href="#a">A</a></li>
             <li><a href="#b">B</a></li>
             <li><a href="#c">C</a></li>
             <li><a href="#d">D</a></li>
             <li><a href="#e">E</a></li>
             <li><a href="#f">F</a></li>    
              .....         
       </ul>
    </div>
</div>

To set a class active the code is:

将类设置为活动代码是:

 <li class="active"><a href="#f">F</a></li>

How can I do that with jQuery?

我怎样才能用 jQuery 做到这一点?

回答by Zim

You can set it active like this..

您可以像这样将其设置为活动状态..

$('.nav li').click(function(){
    $('.nav li').removeClass('active');
    $(this).addClass('active');
})

Bootply

Bootply

回答by Tom Benyon

My solution works well when creating restful sites.

我的解决方案在创建宁静的网站时效果很好。

The main JS is here:

主要的JS在这里:

$(document).ready(function() {
    var main_route = (window.location.pathname.split("/")[1]);
    $('#navbar_' + main_route).addClass('active');
});



It works by:



它的工作原理是:

1)Finding the main route of the URL. For example if the url was "http://www.benyon.com/projects/first_project" it would get "projects".

1)找到URL的主路由。例如,如果 url 是“ http://www.benyon.com/projects/first_project”,它会得到“projects”。

JS snippet

JS 片段

var main_route = (window.location.pathname.split("/")[1]);



2)It then uses that to refer to the ID of the list element for that particular button using concatenation. For example: ‘#navbar_' + main_routeis the same as ‘#navbar_projects'.

2)然后它使用它来引用使用串联的特定按钮的列表元素的 ID。例如: ‘#navbar_' + main_route与 相同‘#navbar_projects'

It then adds the “active” class using addClass(‘active').

然后它使用addClass(‘active').

JS snippet

JS 片段

$('#navbar_' + main_route).addClass('active');

HTML snippet

HTML 片段

<li id="navbar_projects"><a href="/projects">Projects</a></li>



The Downside



不足之处

For this to work your routes need to have the same name as the index of the element you want to highlight.

为此,您的路线需要与您要突出显示的元素的索引具有相同的名称。

回答by A. Wolff

You could use this code:

您可以使用此代码:

SEE DEMO

看演示

$('.nav li').click(function(){
    $(this).addClass('active').siblings().removeClass('active');
})