這裏是我的JS代碼,它將一個活動類添加到所有包含與我當前的URL匹配的href路徑的所有<a>
對象的父類。將活動類添加到菜單中的錯誤文檔對象
aObj = document.getElementById('menuG').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
alert("Button n°"+i+" - Value : "+document.location.href.indexOf(aObj[i].href));
aObj[i].parentElement.className='active';
}
}
我的問題是,有href="/"
的第一個按鈕始終處於活動狀態。
代碼document.location.href.indexOf(aObj[i].href)
總是返回0爲第一個按鈕,我不明白爲什麼。
這裏是我的html代碼:
<ul class="nav navbar-nav" id="menuG">
<li><a href="/">Mes Fichiers</a></li>
<li><a href="historique.html">Historique</a></li>
<li><a href="profil.html">Profil</a></li>
</ul>
感謝您的時間。
謝謝大家。我明白indexof()如何工作。你的解決方案非常棒!謝謝 ! –
沒問題,不客氣。不要忘記,現在你正在尋找一個完全匹配,所以'example.com/index'不會匹配第一個元素。如果您決定更改主頁的URL,但不更新鏈接標記(例如,如果您執行302重定向,則會發生這種情況),則會發生這種情況。 – 2016-01-21 20:21:02