簡體   English   中英

如何根據url中的關鍵字用jquery更改css類

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

我有如下導航欄

<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>

我希望如果網址是www.abc.com/user/profile那么配置文件選項卡類應該選擇附加的類

如果照片然后照片選項卡。

如果我們可以進行部分匹配,但我不確定這是否可行

就像在url我有/user/bookmyBook被選中

一些優雅的變體:

<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');
});

您可能希望關閉location.pathname 假設你給那個<ul>一類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
});

值得注意的事情

  • 我們使用$(function () {...}); 而不是$(document).ready(function() {...}); 它打字更少,效率更高

  • 我們使用String.search() ,它返回字符串"/user/profile"出現的索引 如果找不到該字符串, String.search()將返回-1,所以如果它!= -1 ,它就存在。

  • 我們還使用jQuery.eq( index )將jQuery選擇器選擇的元素視為數組,並返回指定索引的元素。

參考

看看jQuery的.eq 這里 ,和JavaScript的String.search 這里

您可以使用正則表達式獲取所需的部分:

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

那將在user/之后為您提供部分。 然后你可以使用switch語句:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM