Navigazione attiva con jQuery: impossibile applicare una classe predefinita all'ancoraggio

StackOverflow https://stackoverflow.com/questions/302955

  •  08-07-2019
  •  | 
  •  

Domanda

Attualmente sto cercando di creare un menu di navigazione in cui una classe attiva viene applicata alle ancore con hrif che corrispondono all'URL corrente, quindi posso modellare quell'ancora in un modo che lo distingua dal resto del menu.

Questo è il mio 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> 

Questo è il 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');

});

Sto applicando la classe attiva con jQuery, funziona bene fintanto che esiste una corrispondenza tra un anchor href e l'URL della posizione. Se l'URL non corrisponde a nessuna delle ancore, voglio che la classe attiva venga applicata a $ top_item. Quella parte del mio jQuery non funziona.

Non riesco a vedere quale sia l'errore, ma di nuovo sono un po 'Javascript / jQuery n00b. Qualsiasi aiuto sarebbe apprezzato.

È stato utile?

Soluzione

Questo dovrebbe volere che tu voglia: contrassegnare il collegamento corrispondente e, in caso contrario, contrassegnare quello predefinito.

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();

Inoltre, ho trovato un tutorial ufficiale su questo sul sito jQuery Docs - scorrere verso il basso per vedere il codice jQuery. È più stretto del mio, anche se non è su misura per la tua situazione.

Altri suggerimenti

Prova questo codice, è qualcosa che ho messo insieme per l'azienda per cui lavoro.

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

ottima lettura .. ma, devo dare un suggerimento .. anche se JS funziona perfettamente, dovresti davvero tenere tutte le voci dell'elenco dei menu all'interno di un Elenco non ordinato (o Elenco ordinato), .. come best practice .. :)

Penso che tu possa semplificare un po 'questo:

function highlightSelected()
{
  $("h2.subnav a").each(
    function()
    {
      if (location.pathname.indexOf(this.href) > -1)
      {
        $(this).addClass("selected");
      }
    }
  );
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top