想法:我想添加class =“active”到li元素,当特定的链接被点击,这是相当于href和url。Javascript获取从子元素(无jquery)剥离href值分配活动类
问题:我无法选择嵌套在ul里面的href值。 CSS可能会尽早加载样式。 注意:html被注入了php。
代码:
window.onload = function() {
\t
var curURL = window.location.href.split("/").pop(); //Outputs the current page url ex index.php
var linkNow = document.getElementsByClassName("topnav").getElementsByTagName("a").href;//Nesting this does not work but how can it be achieved?
//Loop check which curURL matches the href value, true->assign active class
for (var i = 0; i < link.length; i++) {
if (curURL == linkNow[i]){
linkNow.addClass("active");
break;
}
}
//As soon as the a element has the class="active" the navbar color will change
}
<ul class='topnav'>
<li><a href='index.php'>Home</a></li>
<li><a href='news.php'>News</a></li>
<li><a href='showcase.php'>Showcase</a></li>
<li class='icon'>
<a href='javascript:void(0);' onclick='myFunction()'>⌨</a><!-- responsive icon-->
</li>
</ul>
你不应该需要说 “不jQuery的”。没有标签,它在OP中没有使用,因此答案不应该使用它。 – RobG
对不起。你看我研究了相当数量,并且大多数答案都是针对jQuery的,所以我想澄清;) –