簡體   English   中英

添加基於子頁面URL的活動導航類

[英]Add Active Navigation Class Based on Child Page URL

我有一個基本的側邊菜單結構,它是根據帖子主題動態生成的。 使用以下代碼,我可以在查看各個主題頁面時按預期突出顯示活動鏈接。 但是,在列出所有主題的主頁或索引頁面上,側面導航中的每個錨點元素都被賦予一個“活動”類。 如何防止索引頁面sidenav錨接收“活動”類,同時在各個主題頁面上保留“活動”類?

預先感謝任何能提供一些見識的人...

側面導航結構:

<div class="sidenav">
  <ul>
    <li><a href="//example.com/customer/topic/government">Government</a></li>
    <li><a href="//example.com/customer/topic/hospitality">Hospitality</a></li>
    <li><a href="//example.com/customer/topic/industrial">Industrial</a></li>
  </ul>
</div>

Javascript:

$(function(){
    var current = location.pathname;
    $('.sidenav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

單個主題頁面上使用上述JS的當前輸出:

<div class="sidenav">
  <ul>
    <li><a href="//example.com/customer/topic/government">Government</a></li>
    <li><a href="//example.com/customer/topic/hospitality" class="active">Hospitality</a></li>
    <li><a href="//example.com/customer/topic/industrial">Industrial</a></li>
  </ul>
</div>

使用主題索引頁面上的上述JS的當前輸出(/客戶)

<div class="sidenav">
  <ul>
    <li><a href="//example.com/customer/topic/government" class="active">Government</a></li>
    <li><a href="//example.com/customer/topic/hospitality" class="active">Hospitality</a></li>
    <li><a href="//example.com/customer/topic/industrial" class="active">Industrial</a></li>
  </ul>
</div>

嘗試此操作,以這種方式添加最新密鑰到當前可能是協議問題,您可以始終確保

$(function(){
    var current = location.pathname;
    current = current.substring(current.lastIndexOf('/'));
    $('.sidenav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    });
});

暫無
暫無

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

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