[英]How to remove the active class from first li-item while other one is active using JavaScript(!important))
I am working on an old site where only JavaScript codes are working. 我在仅JavaScript代码有效的旧站点上工作。 Problem is: the active class is working but while clicking on other "li", the li "Home" still remains active. 问题是:活动类正在运行,但是在单击其他“ li”时,li“ Home”仍然保持活动状态。 Please suggest what other code need to be added in JS. 请提出需要在JS中添加哪些其他代码。 Thanks in advance! 提前致谢! The code are: 代码是:
function setActive() { aObj = document.getElementById('navmenu').getElementsByTagName('a'); for (i = 0; i < aObj.length; i++) { if (document.location.href.indexOf(aObj[i].href) >= 0) { aObj[i].className = 'active'; } } } window.onload = setActive;
<div id="navmenu"> <ul> <li><a href="/">Home</a> </li> <li><a href="/Home/Vision">Vision</a> </li> <li><a href="/Home/Career">Career</a> </li> </ul> </div>
When you use indexOf()
, you're testing whether aObj[i].href
is anywhere in document.location.href
, you're not testing whether it exactly matches the path. 当使用indexOf()
,您正在测试aObj[i].href
是否在document.location.href
任何位置,而不是在测试它是否与路径完全匹配。 Since /
is in /Home/Vision
, that test succeeds. 由于/
位于/Home/Vision
,因此测试成功。 Try doing an exact match of document.location.pathname
. 尝试完全匹配document.location.pathname
。
function setActive() { aObj = document.getElementById('navmenu').getElementsByTagName('a'); for (i = 0; i < aObj.length; i++) { if (document.location.pathname == aObj[i].href) { aObj[i].className = 'active'; } } } window.onload = setActive;
<div id="navmenu"> <ul> <li><a href="/">Home</a> </li> <li><a href="/Home/Vision">Vision</a> </li> <li><a href="/Home/Career">Career</a> </li> </ul> </div>
Check if the below link works with you. 检查以下链接是否适合您。
http://jsfiddle.net/FnK9D/16/ http://jsfiddle.net/FnK9D/16/
function setActive(){aObj = document.getElementById('navmenu').getElementsByTagName('a');
for (i = 0; i < aObj.length; i++) {
if (document.location.href.indexOf(aObj[i].href) >= 0) {
aObj[i].className = 'active';
}
}
}
window.onload = setActive;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.