开发者

Apply a class based on the page

I need to apply a class ".selected" to a navigation item when the user is on the corresponding page, so that when the user clicks on "Products", it goes to the products page but the Products nav item remains selected. How can I accomplish this using jQuery? I suppose I would need to get the URL of the page an apply the styl开发者_开发技巧e to the corresponding nav item, correct?


Here is a simple example, if you wish to match the entire URL ('http://example.com/mydir/mypage.html'):

  $(function() {
    var url = window.location;
    $('a[href="' + url + '"]').addClass('selected');
  });

Or, to match the path ('/mydir/mypage.html'):

  $(function() {
    var url = window.location.path;
    $('a[href="' + url + '"]').addClass('selected');
  });


I assume that you'll be doing some sort of AJAX system where you won't be reloading the menu on every click, otherwise this should definitely be done server side. If not, you can use the following

HTML

<ul id='main'>
    <li>menu</li>
    <li>menu</li>
    <li>menu</li>
</ul>​​​

Javascript:

$('ul#main > li').click(function() {
        $('ul#main > li.selected').removeClass('selected');
        this.setAttribute('class','selected');
}​​​​​​​​​);​

Here's a link to try it out: http://jsfiddle.net/6zpJX/


assuming the element you want styled .selected has an id same as the html file currently in the browser:

$(document).ready(function() {
  ...
  var page = window.location.href.match(/\/(\w+).htm/)[1];
  $('#' + page).addClass('selected');
  ...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜