簡體   English   中英

將active_section類添加到菜單的部分

[英]Add active_section class to section of menu

我有一個如下的html菜單...

 <ul class="menu" id="menu"> <ul class='section' id='section_1'> <li><span id='section_title_1' class='section_title'><a href='#' id='section_link_1'>Against the odds.</a></span> <ul> <li id='exhibit_1' class='exhibit_title'><a href="../against-the-odds/introduction"> &rarr; Introduction</a> </li> <li id='exhibit_2' class='exhibit_title'><a href='../against-the-odds/deriving-functions'> &rarr; Deriving functions</a> </li> <li id='exhibit_3' class='exhibit_title'><a href='../against-the-odds/exploiting-odds'> &rarr; Exploiting odds</a> </li> <li id='exhibit_4' class='exhibit_title'><a href='../against-the-odds/betting_history'> &rarr; Betting history</a> </li> </ul> </li> </ul> <ul class='section' id='section_2'> <li><span id='section_title_2' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_2'>Remembering everything.</a></span> <ul> <li id='exhibit_104' class='exhibit_title'><a href='#'>black swans</a> </li> </ul> </li> </ul> <ul class='section' id='section_5'> <li><span id='section_title_5' class='section_title'><a href='http://themathsproject.co.uk' id='section_link_5'>Running faster.</a></span> <ul> <li id='exhibit_107' class='exhibit_title'><a href='#'>possible areas to explore</a> </li> <li id='exhibit_108' class='exhibit_title'><a href='#'>developing the model</a> </li> <li id='exhibit_109' class='exhibit_title'><a href='#'>performance</a> </li> </ul> </li> </ul> <ul class='section' id='section_4'> <div class='bot'> <p><a href='https://www.twitter.com/themathsproject' target="_blank">twitter</a> <br /> <a href='https://www.facebook.com/themathsproject' target="_blank">facebook</a> </p> </div> </ul> </ul> 

它由幾個“節”組成,這些節包含鏈接(與節有關)。 每個部分都有一個主要標題(例如,反對賠率)和幾個子部分(存儲在另一個ul中),例如“派生函數”。 這些小節設置為display: none默認情況下display: none (如果用戶願意,我有jQuery會打開小節)。

問題:

一旦用戶單擊小節鏈接(例如,www.themathsproject.co.uk / against-the-odds / deriving-functions),我希望該小節容納鏈接(在id = section_1的情況下)在頁面上重新打開即可重新加載,以便用戶可以輕松導航至該部分中的其他鏈接。 其他小節將保持關閉。

我想編寫一個jQuery函數,將當前頁面的url與每個部分中的鏈接進行比較,如果找到匹配項,則將“ active_section”類分配給相關部分。 不幸的是,我不知道該怎么做。

我整天都被困住了,進展甚微。

我將不勝感激,

插口

您的帖子有點混亂,因此我將嘗試為您提供一般性提示。

要獲取網址的最后一個元素,請使用

var name = window.href.substr(this.href.lastIndexOf('/') + 1)

現在,您可以獲取所有小節並對其進行迭代(例如,使用jQuery):

$('.sub-section').each(function() {
    if ($(this).attr('id') === name) {
        $(this).addClass('active');
    }
});

如果您的ID與url中的名稱不同,則可以創建字典來映射等效項:

var sectionMap = { "section-name-1": "sectionID1" };

在使用我提供的第一行代碼獲取網址后,您可以執行以下操作:

name = sectionMap[name];

暫無
暫無

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

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