Using jQuery To Add Class Based On URL

后端 未结 4 744
無奈伤痛
無奈伤痛 2021-01-21 14:19

I\'m using jQuery and I\'m trying to add a class to a menu item based on URL. I tried this(found in other topics), but cannot get it to work properly. It adds the class to every

4条回答
  •  臣服心动
    2021-01-21 14:37

    If the element you're adding the current class to has a href value relative to the current page's URL this method will likely be easier for you.

    You could probably simplify this a bit..

    Let's say you're on the following page: http://domain.com/page.html

    var current_location = window.location.href.split('/'); // ['http:', '', '', 'domain.com', 'page.html']
    var page;
    
    page = current_location[current_location.length - 1]; // the length of the current_location array is 5, subtract one to get the value of the 4th index - which is page.html
    
    $('a[href*="' + page + '"]').addClass('current'); // find a link on the page that links to page.html (current page) and add a class of `current` to this URL
    

    Here's an example on jsbin: http://jsbin.com/uzoyis/1

提交回复
热议问题