开发者

How to add a class active in a menu where url has the same pass

开发者 https://www.devze.com 2023-01-28 18:53 出处:网络
I have the following menu. <ul id=\"nav\" class=\"grid_16\"> <li><a href=\"#\">FORSIDE</a></li>

I have the following menu.

<ul id="nav" class="grid_16">
    <li><a href="#">FORSIDE</a></li>
    <li><a href="#">MOBIL</a></li>
    <li><a href="#">PC OG SERVERE</a></li>
    <li><a href="#">TJENESTER</a></li>
    <li><a href="#">DIVERSE</a></li>
    <li><a href="#">OM OSS</a></li>
    <li><a href="#">KONTAKT</a></li>
    <li><a href="#">NETTBUTIKK</a></li>

</ul>

A url path will have under score _ where there is a space. For example PC OG SERVERE will be

 http://www.mywebsite.no/PC_OG_SER开发者_如何学CVERE.asp

DIVERSE will be

http://www.mywebsite.no/DIVERSE.asp

I'd like to add class="active" in a list with jquery. For example when you are in http://www.mywebsite.no/OM_OSS.asp

 .....
 .....
 <li class="active"><a href="#">OM OSS</a></li>
 ....

How can I do it?

Thanks in advance.


You could do something like this:

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

You can change up the regex, etc...but the concept is the same, get the text, compare it to each <li>'s text (since the <a> adds none, you can do it right on the <li>). For much older versions of jQuery you'll need to use .text() instead of the shortcut above, like this:

$("#nav li").filter(function() {
  return $(this).text() == text;
}).addClass("active");

Note we're not using :contains() here, we're doing an exact match, instead of a substring.


You could try something like

$("#nav li a").each(
  function(){
    // Could be that you have to use $(this). Not sure.
    if (this.text() == 'DIVERSE'){
      this.addClass('active');
    } 
  }
);

But I think it would be better to generate this class in the serverside code.


var pathComponents = window.location.pathname.split("/");
var fileName = pathComponents[pathComponents.length - 1];
var documentName = fileName.substr(fileName.length - 4).replace("_", " ");

$('#nav li a:contains(' + documentName + )').parent().addClass('active');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号