简体   繁体   中英

How to apply an active css class to li based on its child <a> href

I have the following markup to show a navigation menu :

<ul class="nav sf-menu">
    <li><a href="@Url.Action("Index","Home")">Home<span></span></a></li>

Now I want to add active class to the li if the current URL is equal to its <a> href.

I have tried the following:

$(function () {

    var url = window.location.pathname,
        urlRegExp = new RegExp(url.replace(/\/$/, '') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
    // now grab every link from the navigation
    $('.sf-menu li').each(function () {
        // and test its normalized href against the url pathname regexp
        if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
            $(this).addClass('active');
        }
    });

});

but I get an error that li does not have a href . How do I get this to work?

The href attribute exists on the <a> element, not the <li> element. You need to check the <a> for the href and then apply the class to the parent <li> .

Here is how I have tweaked your code to target the <a> tag:

jQuery(function () {
    var url = window.location.pathname;

    if (url == '/') {
        jQuery('.sf-menu li > a[href="/"]').parent().addClass('active');
    } else {
        var urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
        jQuery('.sf-menu li > a').each(function () {
            if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                jQuery(this).parent().addClass('active');
            }
        });
    }
});

JSFiddle

I've also placed a check for if the link is / to prevent all the links from being marked as active.

You could also try this simplified version if your links work with it:

jQuery(function () {
    var url = window.location.pathname;
    jQuery('.sf-menu li > a[href="' + url + '"]').parent().addClass('active');
});

尝试这个

$('.sf-menu li >a').each(function () {

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