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

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

    Online demo: http://jsbin.com/otapo

    Paste a test-url into the textbox on that demo page to see it select the corresponding link. Change the textbox value to a new test-url to see it deselect any selected links, and select the new link that corresponds to the url provided.

    Adding Class 'Selected' Based on URL

    var loc = window.location.split("/").slice(-1);
    $("a.selected").removeClass("selected");
    $("a[href$='"+loc+"']").addClass("selected");
    

    This particular example here requires some explaining. Normally I would change this logic, and look for siblings, but considering the fact that you're interested in wrapping each link in an LI, these links wouldn't be siblings anymore.

    I could write this to work with parent LI's around each link, but then I'm not sure if you would test it immediately with parent LI's, and think that it doesn't work. That being said, if you implement the following solution, you could improve this solution. In its current state (not very pretty), it will work either way.

    Convert the Links into an UL

    $(".WikiCustomNav").wrapInner("
      ").find("a").wrap("
    • ");

    提交回复
    热议问题