当一个列表项被选中时,我正在使用twitter bootstrap,并尝试使用jquery将“active”类设置为导航列表项。
下面是我的代码
<ul class="nav nav-pills pull-right">
<li id="home"><a href="/">Home</a></li>
<li id="gadget"><a href="/category/gadgets"><span>Gadgets + Geeky</span></a></li>
<li id="toys"><a href="/category/toys"><span>Toys</span></a></li>
<li id="wearables"><a href="/category/wearables"><span>Wearables</span></a></li>
<li id="home_office"><a href="/category/home-office"><span>Home + Office</span></a></li>
<li id="food_drinks"><a href="/category/food-drinks"><span>Food + Drinks</span></a></li>
<li id="kids"><a href="/category/kids"><span>Kids Stuff</span></a></li>
</ul>
<script>
$( document ).ready(function() {
$('ul li').click(function() {
// remove classes from all
$('li').removeClass('active');
// add class to the one we clicked
$(this).addClass("active");
});
});
</script>
但当我单击一个列表项时,在导航项上设置了临时活动类,但页面正在刷新,并显示当前单击的列表项,但没有活动类。
我已经按照Toggle active class in nav bar with JQuery中提到的说明进行了操作,但没有成功。
有人能指出我错过了什么吗?
谢谢
发布于 2013-02-27 14:19:11
此脚本在重定向发生后运行,因此这对您来说应该是有效的。我们正在向活动链接添加一个虚拟类'activeLink‘,并根据该活动链接选择列表。
$(function(){
$('ul li a').removeClass('activeLink');
var url = window.location.pathname,
// create regexp to match current url pathname also to match the home link
urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/,''));
// now grab every link from the navigation
$('.ul li a').each(function(){
// and test its normalized href against the url pathname regexp
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).addClass('activeLink');
}
});
$('li').removeClass('active');
$('a.activeLink').closest('li').addClass('active');
});
https://stackoverflow.com/questions/15097223
复制相似问题