Adding active class to current page in nav with jQuery

 ̄綄美尐妖づ 提交于 2019-12-04 20:35:01

That's happening because you are using the ^= selector. That means 'startWith' so since all urls start with '/' the 'active' class is being added to all of them.

Replace it with the equal selector and it should work.

$('nav li a[href="/' + location.pathname.split("/")[1] + '"]').addClass('active');

A simpler approach is compare the href property of link to page url

$('nav li a').filter(function(){
  return this.href === location.href;
}).addClass('active');

Although the href attribute only contains a path, the href property in the DOM contains the full url

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