使用 jQuery 进行主动导航 - 无法将默认类应用于锚点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/302955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:54:48  来源:igfitidea点击:

Active navigation with jQuery - can't apply a default class to anchor

jquerynavigation

提问by timkl

I am currently trying to make a navigation-menuwhere an active-classis applied to the anchors whose hrefattributes that match the current URL, so I can style that anchor in a way that makes it stand out from the rest of the menu.

我目前正在尝试将navigation-menuwhere anactive-class应用于其href属性与当前 URL 匹配的锚点,因此我可以以某种方式设置该锚点的样式,使其从菜单的其余部分中脱颖而出。

This is my mark-up:

这是我的标记:

<div id="sidebar">

  <h2>Navigation menu</h2>
  <h2 class="subnav"><a href="menu1/menu_item1">Menu item 1</a></h2>
  <h2 class="subnav"><a href="menu1/menu_item2">Menu item 2</a></h2>
  <h2 class="subnav"><a href="menu1/menu_item3">Menu item 3</a></h2>
  <h2 class="subnav"><a href="menu1/menu_item4">Menu item 4</a></h2>
  <h2 class="subnav"><a href="menu1/menu_item5">Menu item 5</a></h2>

</div> 

This is the jQuery:

这是jQuery:

   jQuery(function($) {

      // get the current url
      var path = location.pathname.substring(1); 

      // defining the top subnav anchor
      var $top_item = $('#sidebar h2:nth-child(2) a'); 

      // defining all subnav anchors
      var $all_items = $('#sidebar h2.subnav a'); 

      // defining the anchors with a href that matches the current url
      var $selected_item = $('#sidebar h2 a[@href$="' + path + '"]'); 

      // setting the selected menu item'class as active
      $selected_item.addClass('active'); 

      // THIS IS WHERE I THINK THE ERROR IS
      // if none of the h2.subnav's has a url that matches 
      // the current location then assume that it's the top one that's active:
      if ($all_items("href") !== path) $top_item.addClass('active');

  });

I am applying the active-class with jQuery, it works fine as long as there is a match between an anchors href and the location url. If the url don't match any of the anchors I want the active-class to be applied to the $top_item. That part of my jQuery doesn't work.

我正在使用 jQuery 应用活动类,只要锚点 href 和位置 url 之间存在匹配,它就可以正常工作。如果 url 与任何锚点都不匹配,我希望将 active-class 应用于$top_item. 我的 jQuery 的那部分不起作用。

I can't see what the error is, but then again I'm somewhat of a Javascript/jQuery n00b. Any help would be appreciated.

我看不出错误是什么,但是我又有点像 Javascript/jQuery n00b。任何帮助,将不胜感激。

回答by Nathan Long

This should do want you want: mark the matching link, and failing that, mark your default one.

这应该是您想要的:标记匹配的链接,如果失败,则标记您的默认链接。

function markActiveLink() {

    //Look through all the links in the sidebar
   $("div#sidebar a").filter(function() {

      //Take the current URL and split it into chunks at each slash
      var currentURL = window.location.toString().split("/");

      //return true if the bit after the last slash is the current page name
      return $(this).attr("href") == currentURL[currentURL.length-1];

    //when the filter function is done, you're left with the links that match.
    }).addClass("active");

   //Afterwards, look back through the links. If none of them were marked,
   //mark your default one.
   if($("div#sidebar a").hasClass("active") == false) {
      $("div#sidebar h2:nth-child(2) a").addClass("active");
    }
 }

markActiveLink();

Also, I found an official tutorial on this on the jQuery Docs site- scroll to the bottom to see the jQuery code. It's tighter than mine, although it's not tailored to your situation.

另外,我在 jQuery Docs 站点上找到了关于此的官方教程- 滚动到底部以查看 jQuery 代码。它比我的更紧,尽管它不适合您的情况。

回答by jrutter

Give this code a shot, its something I put together for the company that I work for.

试一试这段代码,它是我为我工作的公司整理的。

// highlight tab function
var path = location.pathname;
var home = "/";
$("a[href='" + [path || home] + "']").parents("li").each(function() {   
    $(this).addClass("selected");
});

回答by jrutter

great read.. but, I have to make a suggestion.. even if the JS works perfectly, you really should keep all menu list items within an Unordered List (or Ordered List),.. as a best practice.. :)

很棒的阅读……但是,我必须提出一个建议……即使 JS 运行良好,您也确实应该将所有菜单列表项保留在无序列表(或有序列表)中,……作为最佳实践……:)

回答by Tom

I think you can simplify this a bit:

我认为你可以简化一下:

function highlightSelected()
{
  $("h2.subnav a").each(
    function()
    {
      if (location.pathname.indexOf(this.href) > -1)
      {
        $(this).addClass("selected");
      }
    }
  );
}