我正在尝试让我的引导站点动态地将活动类应用于当前页面链接。
主页|问题|登录/注册 |视图 |新
问题页面中有多个页面,因此site.com/questions/index&例如site.com/questions/new。该链接适用于site.com/questions/index
我有我的javscript将活动类添加到问题/索引链接但不是我想要的问题/新。
var url = window.location;
// Will only work if string in href matches with location
$('ul.nav a[href="'+ url +'"]').parent().addClass('active');
// Will also work for relative and absolute hrefs
$('ul.nav li').filter(function() {
return this.href == url;
}).parent().addClass('active');
有一些帮助吗?
答案 0 :(得分:0)
请使用整页运行代码段并查看示例。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a>
</li>
<li><a href="#about">About</a>
</li>
<li><a href="#contact">Contact</a>
</li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">
</script>
<script>
//Click on any li in ul with class 'navbar-nav'
$('ul.navbar-nav li').click(function(e) {
var $this = $(this); // declare variable for current li that we click
$('ul.navbar-nav').find('li.active').last().removeClass('active') //find all li that class class active and remove
$this.addClass('active'); //add 'active' class to current li.
});
</script>
</body>
</html>