Active state on nav after page refresh

空扰寡人 提交于 2019-12-13 04:26:57

问题


This is the code I am using at the moment to add an active state to an item after your clicked on one of the navigation and the page has been redirected.

I was wondering if there was another way to do it because it works only on my local machine but not on a server.

 $(document).ready(function () {         
        current_page = document.location.href            
        if (current_page.match(/home/)) {
            $("ul#ulMenuNav li:eq(0) a").addClass('navActive');
        } else if (current_page.match(/about/)) {
            $("ul#ulMenuNav li:eq(1) a").addClass('navActive');
        } else if (current_page.match(/location/)) {
            $("ul#ulMenuNav li:eq(2) a").addClass('navActive');
        } else if (current_page.match(/staff/)) {
            $("ul#ulMenuNav li:eq(3) a").addClass('navActive');
        } else if (current_page.match(/contact/)) {
            $("ul#ulMenuNav li:eq(4) a").addClass('navActive');
        } else { 
            $("ul#ulMenuNav li a").removeClass('navActive');
        };

    });

回答1:


You can try this: http://jsfiddle.net/jaiprakashsah/thrDq/

var url = document.location.href;
var str = url.substr(0, url.lastIndexOf('/'));
var nUrl = str.substr(str.lastIndexOf('/')+1);

$('ul#ulMenuNav li a:contains('+nUrl+')').addClass('active');



回答2:


How about:

$(document).ready(function () {         
  var current_page = document.location.href;

  $('ul#ulMenuNav li a').removeClass('navActive');
  $('ul#ulMenuNav li a[href*="'+current_page+'"]').addClass('navActive');

});


来源:https://stackoverflow.com/questions/14476591/active-state-on-nav-after-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!