动态地将活动类应用于nav li [英] dynamically apply active class to nav li
问题描述
我在我的文件中包含了一个头文件,如include。在标题是导航栏。
I have included a header to my files as in include. In the header is the nav bar.
如何使用jQuery将 class =active
应用到相关的 li
。
How do I, using jQuery, apply class="active"
to the relevant li
.
我可以想到的唯一方法是在实际页面上设置一个变量,应用一个等于相关页面的变量的id,如果函数所以如果他们匹配应用一个类到li。
The only way I could think of doing it is to set a variable on the actual pages, apply an id that is equal to that variable of the relevant page and if function so if they match apply a class to the li.
但是,我认为必须有一个更简单的方法来实现这一点。
However, I thought there must be a simpler way of achieving this.
<ul class="nav nav-pills right" id="div">
<li id="home" class="active">
<a href="index.php">Home</a>
</li>
<li id="search">
<a href="search.php">Search</a>
</li>
<li id="contact">
<a href="contact.php">Contact</a>
</li>
</ul>
推荐答案
一个简单的方法是每页脚本:
An easy way to do this would be to have a script per page:
$('#home').addClass('active'); // for home page
您可以尝试将href与当前网址进行匹配:
You could try and match the href to the current url:
var path = window.location.pathname.substring(1);
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
这篇关于动态地将活动类应用于nav li的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!