简体   繁体   中英

How can i change the css class based on keywords in url with jquery

I have the navigation bar as below

<ul>
  <li class="selected"><a href=">My Profile</a></li>
  <li><a href="">xxxx</a></li>
  <li><a href="">mybook</a></li>
  <li><a href="">Photos <span>4</span></a></li>
  <li><a href="">Profile List</a></li>
</ul>

I want that if the url is www.abc.com/user/profile then profile tab class should have class selected attached

If photos then photo tab.

If we can have partial match that will be good but i am not sure if thats possible

like in url i have /user/book and myBook gets selected

Some elegant variant:

<ul class="menu">
  <li><a class="profile" href="/user/profile">My Profile</a></li>
  <li><a class="book" href="/user/book">My Book</a></li>
</ul>

$(document).ready(function () {
  var page = document.location.href.split('/').slice(-1)[0];
  $('.menu .' + page).addClass('selected');
});

You would want to switch off of location.pathname . Granted that you give that <ul> a class of nav :

$(function () {
    if (location.pathname.search("/user/profile") != -1) {
        // page is /user/profile
        $("#nav li").eq(0).addClass("selected");
    } else if (location.pathname.search("/user/photos") != -1) {
        // page is some/thing
        $("#nav li").eq(3).addClass("selected");
    }
    ... etc
});

Things to notice

  • We use $(function () {...}); as opposed to $(document).ready(function() {...}); . It is less typing and more efficient

  • We use String.search() , which returns the index at which the string "/user/profile" appears. If the string is not found, String.search() will return -1, so if it != -1 , it exists.

  • We also use jQuery.eq( index ) this treats elements selected by a jQuery selector as an array and returns the element of the specified index.

References

Check out jQuery's .eq here , and JavaScript's String.search here

You can grab the part you want with regex:

var userPage = /user\/(.+)/.exec(location.href)[1];

That will give you the part after user/ . Then you could use a switch statement:

switch (userPage) {
  case 'profile':
    ...
    break;
  case 'book':
    ...
    break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM