我使用load()
方法从HTML文件加载导航栏。我希望每个<li>
的活动类动态更改。我尝试了很多选项,但它没有用。
以下是我保存为navigation.html
的导航条形码:
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="navbar-header">
<a class="navbar-brand" href="#">Theatre Count</a>
</div>
<div>
<ul class="nav nav-pills pull-left" id="nav">
<li><a href="home.html"><span class="glyphicon glyphicon-home"></span> Home</a></li>
<li class="active"><a href="status.html"><span class="glyphicon glyphicon-flag"></span> Status</a></li>
<li><a href="#"><span class="glyphicon glyphicon-picture"></span> Live Images</a></li>
<li><a href="reports.html"><span class="glyphicon glyphicon-stats"></span> Reports</a></li>
<li><a href="#"><span class="glyphicon glyphicon-briefcase"></span> Archive</a></li>
</ul>
</div>
<button type="button" class="btn btn-primary pull-right logout"><span class="glyphicon glyphicon-log-out"></span> Log Out</button>
</nav>
以下是我的status.html
网页代码:
<body>
<script>
$(document).ready(function(){
$('#navigation').load('navigation.html');
});
</script>
<script>
$("#nav li a").on("click", function(){
$("#nav li").removeClass("active"); //Remove any previously "active" li
$(this).closest("li").addClass("active"); //Set click li as active
});
</script>
<div id="navigation"></div>
</body>
这里我的活动类脚本无效。
答案 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>
&#13;
答案 1 :(得分:0)
这是一个快速,简单和简短的jquery代码,可以很好地满足这一要求。
// Sets active link in Bootstrap menu
// Add this code in a central place used\shared by all pages
// like your _Layout.cshtml in ASP.NET MVC for example
$('a[href="' + this.location.pathname + '"]').parents('li,ul').addClass('active');
现金: https://www.codementor.io/tips/2948713286/how-to-set-active-class-to-nav-menu-from-twitter-bootstrap