【问题标题】:jQuery add class .active on menujQuery在菜单上添加类.active
【发布时间】:2011-06-19 11:20:56
【问题描述】:

我有一个问题。

当相关页面打开时,我想在项目菜单上添加“活动”类。

菜单很简单:

<div class="menu">

<ul>
<li><a href="~/link1/">LINK 1</a>
<li><a href="~/link2/">LINK 2</a>
<li><a href="~/link3/">LINK 3</a>
</ul>

</div>

在 jQuery 中,我需要检查 url 是否为 www.xyz.com/other/link1/

如果是这个,我想在link1的'a'元素中添加一个类。

我尝试了很多解决方案,但没有任何效果。

【问题讨论】:

    标签: jquery menu


    【解决方案1】:

    Click here jsFiddle 中的解决方案

    你需要的是你需要得到window.location.pathname,然后从中创建正则表达式并针对导航hrefs进行测试。

    $(function(){
    
        var url = window.location.pathname, 
            urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
            // now grab every link from the navigation
            $('.menu a').each(function(){
                // and test its normalized href against the url pathname regexp
                if(urlRegExp.test(this.href.replace(/\/$/,''))){
                    $(this).addClass('active');
                }
            });
    
    });
    

    【讨论】:

    • 哦,你是赢家!谢谢老哥!
    • 这对我有用,除了在主页上。出于某种原因,它将所有导航链接设置为活动状态。 jsFiddle 中的示例更改为 var url = "/"
    • 尝试将 urlRegExp 行更改为 urlRegExp = new RegExp(url == '/' ? window.location.origin + '/?$' : url.replace(/\/$/,''));
    • 太棒了 - 使用 cmets 中的 urlRegExp 效果很好:)
    • 查看替代方案,更优雅的决定:stackoverflow.com/a/17706697/2332416
    【解决方案2】:

    对我来说更简单的方法是:

    var activeurl = window.location;
    $('a[href="'+activeurl+'"]').parent('li').addClass('active');
    

    因为我的链接指向绝对网址,但如果您的链接是相对的,那么您可以使用:

     window.location**.pathname**
    

    【讨论】:

    • 如果您打算将其与pathname 第二种样式一起使用,请确保您不包含星号,我相信 OP 将其放在那里是为了强调,但它们并没有像这样渲染。因此,您需要使用window.location.pathname HTH。
    • 这是一个很好的解决方案,我稍作修改以确保它会影响菜单中的链接。因为在正文内容中可能存在具有相同链接的链接,并且如果父元素以某种方式是列表项,这可能会导致一些 css 问题。或者,如果页脚中有一个快速菜单列表,它也会受到影响。 $('#primaryNav a[href="'+activeURL+'"]').parent('li').addClass('active'); 这确保它只在我想要的位置添加活动类。
    【解决方案3】:

    获取 LI 元素,循环,检查 HREF:

    $('.menu').find('a').each(function() {
        if($(this).attr('href').indexOf('www.xyz.com/other/link1/')>0) {
              $(this).addClass('active');
        }
    })
    

    【讨论】:

    • 还没有...我需要查看部分 url 是否包含一些单词,如果为真我添加类...
    【解决方案4】:

    看看这个这个有效

    HTML

    <div class="menu">
    
        <ul>
            <li><a href="~/link1/">LINK 1</a>
            <li><a href="www.xyz.com/other/link1">LINK 2</a>
            <li><a href="~/link3/">LINK 3</a>
        </ul>
    
    </div>
    

    jQuery

    $(document).ready(function(){
        $(".menu ul li a").each(function(){
            if($(this).attr("href")=="www.xyz.com/other/link1")
                $(this).addClass("active");
        })
    })
    

    【讨论】:

    • 请详细说明 Toro 我可以帮助您
    【解决方案5】:

    Wasim 从这里发布的几篇帖子的回答与宣传的一样:

    http://jsfiddle.net/Realto619/jKf3F/1/

    【讨论】:

      【解决方案6】:

      在向菜单上的“a”元素添加类时,没有其他“addClass”方法对我有用:

      $(function () {
              var url = window.location.pathname,
          urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");  
              $('a').each(function () {
                                  if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                      $(this).addClass('active');
                  }
              });
          });
      

      我花了四个小时才找到它。

      【讨论】:

        【解决方案7】:

        window.location.href会给你当前的url(如浏览器地址所示)。解析并检索相关部分后,您会将其与每个链接 href 进行比较,并将 active 类分配给相应的链接。

        【解决方案8】:

        使用 window.location.pathname 并将其与您的链接进行比较。你可以这样做:

        $('a[href="~/' + currentSiteVar + '/"').addClass('active');
        

        但首先您必须准备 currentSiteVar 以将其放入 selecor。

        【讨论】:

          【解决方案9】:

          我猜你正在尝试混合 Asp 代码和 JS 代码,但在某些时候它会破坏或不能正确地原谅绑定调用。

          也许您可以尝试使用委托。它将减少何时绑定点击事件的复杂性。

          一个例子是:

          $('body').delegate('.menu li','click',function(){
             var $li = $(this);
          
             var shouldAddClass = $li.find('a[href^="www.xyz.com/link1"]').length != 0;
          
             if(shouldAddClass){
                 $li.addClass('active');
             }
          });
          

          看看是否有帮助,它使用来自 jQuery 的 Attribute Starts With Selector

          【讨论】:

          • 使用 asp.net 是的,但不是 ID,一切正常,我想匹配部分 url,例如 /link1/,如果匹配,我将在相关菜单上添加特定类项目(我可以用不同的类调用)...
          • 您好 Toro,我已经更新了示例,看看是否有帮助。它使用 jQuery 中的“属性开头”选择器。
          【解决方案10】:

          这对我有用:D

              function setActive() {
                aObj = document.getElementById('menu').getElementsByTagName('a');
                for(i=0;i<aObj.length;i++) {
                  if(document.location.href.indexOf(aObj[i].href)>=0) {
                    var activeurl = window.location;
                    $('a[href="'+activeurl+'"]').parent('li').addClass('active');
                  }
                }
              }
          
              window.onload = setActive;
          

          【讨论】:

            【解决方案11】:
            <script type="text/javascript">
                jQuery(document).ready(function($) {
                var url = window.location.pathname,
            urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); 
                $("#navbar li a").each(function() {//alert('dsfgsdgfd');
                if(urlRegExp.test(this.href.replace(/\/$/,''))){
                $(this).addClass("active");}
            });
            }); 
            </script>
            

            【讨论】:

              【解决方案12】:

              设置活动菜单,他们有很多方法可以做到这一点。现在,我分享给你一种通过 CSS 设置活动菜单的方法。

                  <a href="index.php?id=home">Home</a>
                  <a href="index.php?id=news">News</a>
                  <a href="index.php?id=about">About</a>
              

              现在,你只需设置 $_request["id"] == "home" thì echo "class='active'" ,我们就可以对其他人做同样的事情。

              <a href="index.php?id=home" <?php if($_REQUEST["id"]=="home"){echo "class='active'";}?>>Home</a>
              <a href="index.php?id=news" <?php if($_REQUEST["id"]=="news"){echo "class='active'";}?>>News</a>
              <a href="index.php?id=about" <?php if($_REQUEST["id"]=="about"){echo "class='active'";}?>>About</a>
              

              我觉得对你有用。

              【讨论】:

              • 如果我们使用 PHP 框架,我认为检查当前控制器或动作很容易。我们可以比较控制器或动作来设置活动链接菜单。我使用 Yii 框架:Yii::app()->controller->id 和 Yii::app()->controller->action->id
              【解决方案13】:
              $(function() {
                   var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
                   $(".nav li").each(function(){
                        if($('a',this).attr("href") == pgurl || $('a', this).attr("href") == '' )
                        $(this).addClass("active");
                   })
              });
              

              【讨论】:

                【解决方案14】:

                这对我有用,基本上导航是一样的

                <div id="main-menu">
                  <ul>
                    <li><a href="<?php echo base_url();?>shop">SHOP</a>
                    <li><a href="<?php echo base_url();?>events">EVENTS</a>
                    <li><a href="<?php echo base_url();?>services">SERVICES</a>
                  </ul>
                </div>
                

                假设您在以下网址: http://localhost/project_name/shop/detail_shop/

                并且您希望“SHOP”li 链接使类“活动”,以便您可以直观地指示它是活动导航,即使您在“detail_shop”的“商店”子页面。

                javascript:

                var path = window.location.pathname;
                var str = path.split("/");
                var url = document.location.protocol + "//" + document.location.hostname + "/" + str[1] + "/" + str[2];
                
                $('#main-menu a[href="' + url + '"]').parent('li').addClass('active');
                
                1. str 将得到 ,project_name,shop,detail_shop
                2. document.location.protocol 将获得 http:
                3. document.location.hostname 将获得 localhost
                4. str[1] 将获得 project_name
                5. str[2] 将获得 shop

                基本上这将匹配导航中的链接,其 href 属性以“shop”开头(或任何二级目录)。

                【讨论】:

                • 欢迎来到 StackOverflow!虽然答案总是很受欢迎,但这个问题是 6 年前提出的,并且已经有了一个公认的解决方案。查看writing great answers 上的文档,了解如何让您的答案发挥作用的一些提示:)
                【解决方案15】:
                    let path = window.location.href;
                    $('#nav li a').each(function() {
                        if (this.href === path) {
                            $(this).addClass('activo');
                        }else{
                            $(this).removeClass('activo')
                        }
                        
                    })
                    
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-11-01
                  相关资源
                  最近更新 更多