簡體   English   中英

jQuery-將活動類添加到菜單中的子菜單

[英]jQuery - Adding active class to submenus in a menu

我有一個側邊欄菜單,該菜單欄用於在我的網站上導航,我希望能夠將活動類動態添加到適當的菜單項中。 我嘗試使用下面的代碼,但是它似乎沒有做任何事情。

    var page = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
    $('ul li a[href="'+ page +'"]').parent().addClass('active');
    $('ul li a').filter(function() {
        return this.href == page;
    }).parent().addClass('active');

我可能對選擇器的語法有誤,因此在下面添加了一個側邊欄代碼段。

    <div id="sidebar" class="nav-collapse ">
        <ul class="sidebar-menu" id="nav-accordion">
            <li>
                <a href="dash.php">
                    <i class="fa fa-dashboard"></i>
                    <span>Home</span>
                </a>
            </li>

            <li class="sub-menu">
                <a href="javascript:;" >
                    <i class="fa fa-cogs"></i>
                    <span>Tools</span>
                </a>
                <ul class="sub">
                    <li><a href="index.php">Uptime</a></li>
                </ul>
            </li>
        </ul>
    </div>

我建議最簡單的方法是過濾<a>元素的集合,以查看哪個href屬性等於當前頁面,然后將'active'類名添加到最接近的祖先<li>元素:

// caching the URL of the page:
var pageURL = document.location.href;

// selecting all <a> elements within the element with the
// id of 'nav-accordion'; then using the filter() method
// to filter the collection returned by the selector:
$('#nav-accordion a').filter(function (index, anchorEl) {

    // only those elements for which this assessment returns
    // Boolean true will be retained.
    // here we test that the 'href' property (not the attribute),
    // which is an absolute URL, is equal the current page's URL:
    return anchorEl.href === pageURL;

// for those elements remaining in the collection we navigate to
// each retained element's closest ancestor '<li>' element and
// and then add the 'active' class-name to that <li>:
}).closest('li').addClass('active');

參考文獻:

window.location不返回字符串。 如果打開瀏覽器的開發人員工具並進行檢查,您將看到它是一個對象。 不知道要使用什么值,但是我認為您應該從pathname屬性開始,例如, var path = window.location.pathname; 然后執行一些正則表達式以獲取頁面名稱(如有必要)。

嘗試這個

$( "#sidebar" ).on('click', function() {
$(this).addClass('active').siblings().removeClass('active');
});

我希望這有幫助

暫無
暫無

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

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