[英]Trying to dynamically change “active” class in nav-bar - Node.js/Express/Handlebars
I am having a slight issue in trying to get the "active" class set when I click on the link so that I know which page I am in. Currently what happens is when I click on a different tab it sets it "active" but then goes away when the page is loaded. 我在单击链接时尝试获取“活动”类集时遇到一个小问题,以便知道我所在的页面。当前发生的情况是,当我单击其他选项卡时,将其设置为“活动”,但是然后在页面加载后消失。
I am using Node.js, Express, Handlebar and Bootstrap. 我正在使用Node.js,Express,Handlebar和Bootstrap。 I have a feeling it has to do something with the fact that the class="nav-link active" is in the < a > tag instead of the < li > tag? 我觉得它必须与class =“ nav-link active”位于<a>标记而不是<li>标记中有关吗?
Please also find a quick video of the issue described: 另请找到有关问题的快速视频:
https://imgur.com/a/xrV8kDv https://imgur.com/a/xrV8kDv
thanks in advance! 提前致谢!
layout.handlebars layout.handlebars
<div class="container">
<div class="header clearfix">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Home App</a>
<ul id="navbarMenu" class="nav nav-pills">
{{#if user}}
<li id="dashboardNav" class="nav-item">
<a class="nav-link active" href="/">Dashboard</a>
</li>
<li id="accountNav" class="nav-item">
<a class="nav-link" href="/users/account">Account</a>
</li>
<li id="logoutNav" class="nav-item">
<a class="nav-link" href="/users/logout">Logout</a>
</li>
{{else}}
<li class="nav-item">
<a class="nav-link" href="/users/login">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/users/register">Register</a>
</li>
{{/if}}
</ul>
</nav>
</div>
<script type="text/javascript">
$('ul.nav-pills li').on("click", "a", function() {
alert("test");
$(this).siblings().removeClass("nav-link active");
$(this).addClass("nav-link active");
//alert($this.child().href);
});
</script>
解决方案是实际上使用句柄{{#if}}块语句在服务器端执行此操作,并将句柄从路由传递给适当的变量。
In the view (handlebars) add if condition: 在视图(车把)中添加以下条件:
<a class="nav-link {{#if path "foo"}} active {{/if}}" href="/foo">Dashboard</a>
In the server side (route or controller that render the view) Edit it and pass the path variable: 在服务器端(渲染视图的路由或控制器)中,对其进行编辑并传递path变量:
router.get('/foo', function (req, res, next) {
res.render('foo', { title: 'foo' ,path:"foo",});
});
Do that for each page you want to add active css class for each anchor. 对您要为每个锚点添加活动CSS类的每个页面执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.