MVC with Bootstrap Navbar - Set Selected Item to Active

后端 未结 7 1506
抹茶落季
抹茶落季 2020-12-13 10:05

I\'m learning Bootstrap and can\'t get the selected item into an \"active\" state. The active state remains on the default item. The newly selected/clicked item changes to

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 10:49

    The JavaScript isn't working because the page is getting reloaded after it runs. So it correctly sets the active item and then the page loads because the browser is following the link. Personally, I would remove the JavaScript you have because it serves no purpose. To do this client side (instead of the server side code you have), you need JavaScript to set the active item when the new page loads. Something like:

    $(document).ready(function() {
        $('ul.nav.navbar-nav').find('a[href="' + location.pathname + '"]')
            .closest('li').addClass('active');
    });
    

    I recommend adding an id or other class to your navbar so you can be sure you have selected the correct one.

提交回复
热议问题