开发者

Apply a class depending on current URL | Jquery

开发者 https://www.devze.com 2023-01-20 21:17 出处:网络
I have a main navigation but I need to apply the class of \'current\' to the <li> if it matches the URL I have specified it should.

I have a main navigation but I need to apply the class of 'current' to the <li> if it matches the URL I have specified it should.

This is what I have:

$(function() {

  var url = location.pathname;

  if(url.indexOf('girls')) {
    $("li#nav-01").addClass('current');
  }

  if(url.indexOf('boys')) {
    $("li#nav-02").addClass('current');
  }

  if(url.indexOf('capes')) {
    $("li#nav-03").addClass('current');
  }

  if(url.indexOf('about_us')) {
    $("li#nav-04").addClass('current');
  }

  if(url.indexOf('contact')) {
    $("li#nav-05").addClass('current');
  }

  if(url.indexOf('frequently_asked_questions')) {
    $("li#nav-06").addClass('current');
  }
});

and then

<div id="nav-main"> 
<u开发者_开发知识库l class="navmain"> 
<li id="nav-01" class=""><a href="../girls/">Girls</a></li> 
<li id="nav-02" class=""><a href="../boys/">Boys</a></li> 
<li id="nav-03" class=""><a href="../capes/">Accessories</a></li>
...
</ul> 
</div>

This doesn't seem to work so What I am looking for is something that allows me to put the full URL up to a certain directory.

So where I have.

'if(url.indexOf...'

I'd like to have something along the lines of:

'if(url=http://www.siteaddress/directory/...'

So then if the current URL is '.../directoryname/' then the <li> I have specified should be selected ('current') depending on that URL, is.

Thanks for reading.


I'd probably place the potential directory matches in an Array, then look for the index of the directory in the array, and use that index number to specify which ID you want to use.

Because the index will be 0 based, I've added 1 to the index to give you a 1 based index like your navs.

$(function() {

  var arr = ['girls','boys','capes','about_us','contact','frequently_asked_questions'];
  var dir = location.pathname.split('/')[1];
  var index = $.inArray( dir, arr ) + 1;
  $("#nav-0" + index).addClass('current');

});
  • arr stores the directory names
  • dir is the pathname split on the / character. The item at index [1] should be the first directory.
  • index stores the result of the $.inArray method, which iterates through the arr Array looking for a match to dir, and returns the index number. (Again 1 is added to match your indexing.)
  • Then the index is concatenated into the selector, to select the proper one.

EDIT: Changed it to not use a regex for the split. Shouldn't be necessary.


Why even use an array?

using the same dir var from patrick dw's code...

  var dir = location.pathname.split('/')[1];
  $('ul.navmain').find('a[href*="' + dir + '"]').parent().addClass('current');
0

精彩评论

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