获取url路径并在li上添加活动类

我尝试抓住url路径,然后在li示例中添加活动类:www.mysite.com/?p = xxxx

x将根据用户点击的链接而改变

我试过这个:

 var text = window.location.href.match(/http:\/\/www\.mysite\.com\/(.+)/)[1].replace(/_/g,' '); $("#nav li").filter(function() { return $.text([this]) == text; }).addClass("active"); 

但没有任何反应。 我做错了什么?

这有效!

 $(document).ready(function(){ var full_path = location.href.split("#")[0]; $(".top_menu li a").each(function(){ var $this = $(this); if($this.prop("href").split("#")[0] == full_path) { $(this).parent().addClass("active"); } }); }); 

您可以使用带有属性选择器的结尾 :

 var pid = '1885'; //Get the current value of p $('#nav li a[href$="'+pid+'"]').parent().addClass('active'); 

这将获得href属性在pid中结束的链接(在本例中为1885)。

如果您有2个以相同字符串结尾的值(例如p=1885p=11885 ),那将导致问题。

如何更改类名并使用PHP和jQuery:

  $(document).ready(function(){'; $from_url = $_GET['p']; echo ' $(\'p_' . $from_url . '\').addClass(\'active\'); }); '; } ?> 

例如,在“www.mysite.comhttps://stackoverflow.com/?p=1888”上面将打印:

  

它将为类名为“p_1888”的HTML添加“活动”类。 例如:

 
  • Find vej
  • 这里也解释了 。