簡體   English   中英

如何根據URL和Vanity URL將活動類添加到錨標記?

[英]How to add an active class to an anchor tag based on URL and Vanity URLs?

如果URL為www.mysite.com/home/,則我需要進行此工作,而不是該部分。 如果是www.mysite.com/home/index.aspx,則可以使用,但是如果刪除index.aspx,則不能使用。 它也適用於我擁有的所有其他頁面-page2.aspx,page3.aspx等...

另外,我可能會在頁面上進行URL重寫(因此page2.aspx將是page2,page3.aspx將是page3)

如何調整以下代碼,以便將活動類添加到活動頁面。

jQuery的:

$(function() {
    var pgurl = window.location.href.substr(window.location.href
    .lastIndexOf("/")+1);
    $("nav a").each(function(){
        if($(this).attr("href") == pgurl || $(this).attr("href") == '')
        $(this).addClass("active");
    })
});

添加類的HTML:

 <nav class="clearfix">
  <a href="index.aspx">Home</a>
  <a href="page2.aspx">Page2</a>
  <a href="page3.aspx">Page3</a>
</nav>

您可以簡單地檢查window.location.pathname

$(function() {
    $("nav a").each(function(){
        if($(this).attr("href") == window.location.pathname || window.location.pathname == '')
        $(this).addClass("active");
    })
});

嘗試這個

var s = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
if(!s)
    document.querySelector("nav > a:first-child").className = "active";
else
    document.querySelector("nav > a[href*='"+s+"']").className = "active";

如果要查找與您要查找的URL部分相同的鏈接,請嘗試以下操作:

var lookup = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
$("a:regex(href, .*"+ lookup +".*)").addClass('active');

聖牛想通了如何做無索引! 我不認為要找到答案就這么困難。 仍然不確定虛榮心。 可能會對此做單獨的帖子。

$(document).ready(function() {

// Add active class to menu
$(function() {
    var pgurl = window.location.href.substr(window.location.href
    .lastIndexOf("/")+1);
    $("nav a").each(function(){
        if($(this).attr("href") == pgurl)
            $(this).addClass("active");
        if (pgurl == '')
                $("nav a:first-child").addClass("active");
    })
});
});

我知道,也許這是愚蠢的解決方案,但是:

  var current_url = window.location.hash.substr(1);
  $('.news #' + current_url).addClass('active');

暫無
暫無

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

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