首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当导航列表项被选中时,需要切换“活动”类

当导航列表项被选中时,需要切换“活动”类
EN

Stack Overflow用户
提问于 2013-02-27 03:05:31
回答 1查看 1.6K关注 0票数 1

当一个列表项被选中时,我正在使用twitter bootstrap,并尝试使用jquery将“active”类设置为导航列表项。

下面是我的代码

代码语言:javascript
复制
            <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中提到的说明进行了操作,但没有成功。

有人能指出我错过了什么吗?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-27 14:19:11

此脚本在重定向发生后运行,因此这对您来说应该是有效的。我们正在向活动链接添加一个虚拟类'activeLink‘,并根据该活动链接选择列表。

代码语言:javascript
复制
 $(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');
    })

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15097223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档