2016-10-25 92 views
0

當前的URL我想活動菜單項上當前的URL,積極的菜單項現在它我的HTML:設置基於使用jQuery

<ul class="header-tools nav navbar-nav"> 
    <li class="mysetting"> 
     <a class="link-menu-active" href="">first title</a> 
    </li> 
    <li class="mysetting"> 
     <a class="link-menu-active" href="">second title</a> 
    </li> 
    <li class="mysetting"> 
     <a class="link-menu-active" href="">third title</a>          
    </li> 
</ul> 

,這是我的jQuery代碼:

$(".header-tools.nav.navbar-nav li").each(function() { 
    var navItem = $(this); 
    if($(navItem).find("a").attr("href") == location.href) { 
     navItem.addClass("active"); 
    } 
}); 

或者:

var path = window.location.pathname; 
path = path.replace(/\/$/, ""); 
path = decodeURIComponent(path); 

$(".header-tools.nav.navbar-nav li a").each(function() { 
    var href = $(this).attr('href'); 
    if (path.substring(0, href.length) === href) { 
     $(this).closest('li').addClass('active'); 
    } 
}); 

但是他們都不起作用,我該怎麼辦?

所以感謝

+1

你有沒有嘗試console.log爲你的路徑和href值來查看正在比較和跳過什麼? – MirzaP

+0

爲什麼你想要做這個客戶端? Wordpress已經具有爲當前菜單項(及其父母,如果有的話)提供特定類的功能 - 爲什麼你不能使用它們? (標籤'recaptcha'與這個有什麼關係?) – CBroe

回答

0

對於這個確切的使用情況,您可以檢查當前的路徑相匹配,或包含錨href和採取相應的行動。

$('.mysetting').each(function() { 
    var path = window.location.pathname, 
     href = $(this).find('a').attr('href'), 
     exactMatch = (path === href), // URL is the same as anchor. Useful when your path can contain the href of multiple links 
     closeMatch = (path.indexOf(href) !== -1); // URL contains anchor. 
                // Useful when you don't know if query strings and other crap will be appended/prepended to your links 

    if (exactMatch /* or closeMatch depending on your preference*/) { 

     $(this).addClass('active'); 
    } 
}) 

雖然,在上述意見如前所述,WP內置在處理正是這種情況,有很多比幾行JavaScript代碼,你可以拿出更強大的導航功能。