[英]Set link of my navbar active with bootstrap
I try to set active the element of my navbar when I click on the button. 当我单击按钮时,我尝试将导航栏的元素设置为活动状态。
My navbar is like that: 我的导航栏是这样的:
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?
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. 1)查找URL的主要路由。 For example if the url was " http://www.benyon.com/projects/first_project " it would get "projects". 例如,如果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. 2)然后使用它通过串联引用该特定按钮的列表元素的ID。 For example: '#navbar_' + main_route
is the same as '#navbar_projects'
. 例如: '#navbar_' + main_route
与'#navbar_projects'
相同。
It then adds the “active” class using addClass('active')
. 然后使用addClass('active')
添加“ 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. 为此,您的路线必须与要突出显示的元素的索引具有相同的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.