How Can I Add a “Selected” Class Based on URL with jQuery?

后端 未结 3 1689
一向
一向 2021-01-07 11:34

I have a sidebar list of links in my wikispace theme that currently uses jQuery to apply a class to each of the sidebar links based on the URL after the .com/. You can see

3条回答
  •  情歌与酒
    2021-01-07 12:15

    Want to see some deep jQuery magic? This will convert your div into a list (jQuery 1.4+) and do the class mangling:

    $("div.wiki").wrap("
      ").children("a").unwrap().wrap("
    • ").removeAttr("class") .filter("[href='" + ocation.pathname + "']").addClass("selected");

    Ok, how does this work? It:

    • Selects div.wiki;
    • Wraps it in a
        ;
      • Selects the children of the
        (wrap() returns the
        still *not* the);
      • Unwraps them, meaning the <div> is deleted and the links are children to the
          now;
        • Wraps each link in a
        • ;
        • Removes all classes from the links;
        • Filters down to the link(s) that have a href equalling the relative path of the window location; and
        • Adds the selected class to that link.
        Edit: Here is a fully working example that I ran locally under http://localhost/test.html:

        
        
        
        
        
        
        
        
        
        
        
        
        
        

        Output:

        
        

        If you want to find out what version of jQuery you have run:

        alert($().jquery);
        

        Edit: jQuery 1.3 version:

        var wiki = $("div.wiki");
        wiki.children("a").wrapAll("
          ").wrap("
        • ").removeAttr("class") .filter("[href='" + location.pathname + "']").addClass("selected") .end().parent().parent().insertAfter(wiki); wiki.remove();

提交回复
热议问题