【问题标题】:dynamically apply active class to nav li动态地将活动类应用于导航 li
【发布时间】:2013-01-18 22:59:32
【问题描述】:

我已经在我的文件中包含了一个标题,就像在 include 中一样。标题中是导航栏。

我如何使用 jQuery 将class="active" 应用于相关的li

我能想到的唯一方法是在实际页面上设置一个变量,应用一个等于相关页面的变量的 id,如果函数匹配,则将一个类应用于 li。

但是,我认为必须有一种更简单的方法来实现这一点。

<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>

【问题讨论】:

  • 我猜这个 html 是在服务器端生成的,你想从某种模板中设置活动的导航元素。你几乎已经有了如何去做的想法。
  • 在下面查看我的答案,无论您的网址末尾是否有“#data”或“?data=test”,都适用于所有情况。

标签: javascript jquery html css nav


【解决方案1】:

一个简单的方法是每页都有一个脚本:

$('#home').addClass('active'); // for home page

您可以尝试将 href 与当前 url 匹配:

var path = window.location.pathname.substring(1);
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');

【讨论】:

  • 没有 jquery 怎么写?带ID不上课,更轻松! document.getElementId('nav>li>a[href="' + path + '"]').parent().addClass('active'); = document.getElementId 不是函数
  • @Jon。这是最简单的方法。您正在寻找的方法是.getElementById,但它不支持选择器,仅支持 Id。用于 HTML5 的 JS 带有一个新的 selectors feature set,但我会坚持使用 jQuery 以实现旧版兼容性。
【解决方案2】:

更紧凑的方式:

$(function(){
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    $('a[href="'+ sPage +'"]').parent().addClass('active');
});

【讨论】:

    【解决方案3】:

    一旦页面加载,它将运行以下代码:

    $(document).ready(function(){
        $('li').removeClass('active');
        $('li a').each(function() {
           $found = $.contains($(this).prop("href"),location.pathname);
           if ($found) {
               $(this).closest('li').addClass('active');
               break;
            }
        });
    });
    

    您也可以使用正则表达式:

    $(document).ready(function(){
        $('li').removeClass('active');
         var regex = /[a-z]+.php/g; 
         var input = location.pathname; 
            if(regex.test(input)) {
               var matches = input.match(regex);
               $('a[href="'+matches[0]+'"]').closest('li').addClass('active');
            }
    });
    

    您可能需要具有与 php 文件类似的 id 名称。

    在这里查看演示:Demo

    【讨论】:

    • 当你在 jquery 中有任何属性的选择器时为什么会出现这个循环?
    • 您的 url 可能有很多次可能有 hash 或 ? .在这种情况下会出现问题。
    【解决方案4】:

    你可以这样做:

    //remove the active class from all items, if there is any
    $('.nav>li').removeClass('active');
    
    //finally, add the active class to the current item
    $('a[href='+ location.pathname.substring(1) +']').parent().addClass('active');
    

    【讨论】:

      【解决方案5】:

      您可以使用 javascript 根据 url 查找当前列表项,方法是在 DOM 加载后将类添加到正确的列表项(例如,使用 JQuery 选择器和 addClass() 对 window.location 进行字符串操作)

      【讨论】:

        【解决方案6】:

        我找到了在我的共享菜单上设置活动(当前)类的例程,但我需要修改它以仅设置父链接,而不是“最近”链接。它适用于没有子菜单的菜单项,但是当单击子菜单项时,页面加载后主菜单上没有指示。 (我需要修改的代码如下)

        (函数($){ $.fn.activeNavigation = 功能(选择器){ var pathname = window.location.pathname 变种扩展位置; 变量href; 变量href = [] $(selector).find("a").each(function(){ // 删除href文件扩展名 extension_position = $(this).attr("href").lastIndexOf('.'); href = (extension_position >= 0) ? $(this).attr("href").substr(0, extension_position) : $(this).attr("href");

                if (pathname.indexOf(href) > -1) {
                    hrefs.push($(this));
                }
            })
            if (hrefs.length) {
                hrefs.sort(function(a,b){
                    return b.attr("href").length - a.attr("href").length
                })
              hrefs[0].closest('li').addClass("current")
            }
        }; })(jQuery);
        

        【讨论】:

          【解决方案7】:

          如果有人仍然在谷歌上查看如何操作,这是我的解决方案

          var path = window.location.href; // full url 
          $('a[href="'+ path +'"]').parent().addClass('active'); // find by selector url
          

          HTML

          <ul class="navbar-nav mr-auto">
              <li class="nav-item">
                  <a class="nav-link" href="http://example.com/">Home</a>
              </li>
              <li class="nav-item">
                  <a class="nav-link" href="http://example.com/history"> History</a>
              </li>
          </ul>
          

          【讨论】:

            猜你喜欢
            • 2014-05-31
            • 1970-01-01
            • 2023-04-04
            • 2019-10-06
            • 2016-08-11
            • 2013-07-03
            • 2019-03-24
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多