简体   繁体   中英

How can I add an “active” class based on the URL?

when a user clicks on a link in the sidebar, it should stay underlined to remind them where they are. i'm trying to use jQuery to add the "active" class to the anchor if they're on the corresponding page. here's what i've got so far:

var pathy = $(location).attr('pathname');
pathy.val().replace(/\\/g, '');
if(pathy == $('#sidebar ul li a').text) {
    $(this).addClass('active');
} 
else {
}

needless to say, it really doesn't work. should i be doing this in php instead?

Try this:

$('#sidebar ul li a').each(function() {
    if ($(this).text() == pathy) {
        $(this).addClass('active');
    }
});

I'm not the best with regex though, so make sure that you return your value first to ensure that it should/shouldn't match.

Edit - after comments below

It doesn't seem like you really need to do much manipulation of the string, so I don't think that a regex is necessary. Also, it will probably be better if you check the href attributes in the a tags rather than their text names, as you may want a href value of "about.php", but a text value of "About Me".

Here is what I would do:

var pathy = location.pathname; //should return something like "/filename.php"
pathy = pathy.slice(1); //this will trim the first "/" character

$('#sidebar ul li a').each(function () {
    if ($(this).attr('href') == pathy) {
        $(this).addClass('active');
    }
});

Here is a sample fiddle .

You are using $(this) in the wrong context. To actually select an item so you can affect it, you would use this instead:

$('[pathname="' + pathy + '"]').addClass('active');

Using the [name="value"] selector you can grab a selector to an item by its attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM