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

后端 未结 3 1657
一向
一向 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:19

    Sounds like you need to do something like this:

    $(".wiki_link").removeClass("wiki_link");   // remove the css class
    $(".wiki_link_new").removeClass("wiki_link_new");
    
    // adds the selected class to the link who's href attribute contains 
    // the current relative path.  Probably needs tweaking based on querystrings
    // and whatnot.
    $(".wiki_link[href~=" + window.location.pathname +"]").addClass("selected");  
    

    If all the links have the same two classes (wiki_link and wiki_link_new) you can remove them both at once by doing removeClass("wiki_link wiki_link_new").

提交回复
热议问题