Javascript从子元素中获取剥离的href值(没有jquery)分配事件类

标签 javascript html nested href children

想法:我想在单击特定链接时将 class="active"添加到 li 元素,该链接等于 href 和 url。

问题:我无法选择嵌套在 ul li 内的 href 值。 CSS 可能会提前加载样式。 注意:html 被注入(inject)了 php。

代码:

window.onload = function () {
	
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()'>&#9000;</a><!-- responsive icon-->
  </li>
</ul>

最佳答案

有很多种方法可以实现,一种是使用选择器直接获取元素,例如

window.onload = function() {
  var href = 'index.php';
  var link = document.querySelector('a[href="' + href + '"]');
  link.parentNode.className = 'active';
}
.active {
  background-color: red;
}
<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>
</ul>

为了与旧版浏览器兼容,您还可以使用更通用的选择器,例如:

var links = document.querySelectorAll('ul a');

甚至:

var links = document.links;

它与几乎所有浏览器兼容,然后循环它们寻找适当的 href 值。

关于Javascript从子元素中获取剥离的href值(没有jquery)分配事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43292498/

相关文章:

javascript - 如何计算小时:Minute format from provided Start Hour-Minute to End Hours-Minute?的持续时间

javascript - 使用动态键创建对象

javascript - 将 XLSX 导入到 JSON(不带工作表名称)

html - 嵌入的 PDF 总是出现在绝对定位的元素上

Android:嵌套 ListView 和项目高度

javascript - 如何使用原型(prototype)获取 anchor 标记的父ID?

javascript - Jquery 从全选中排除一个复选框

html - 将文本与图像一起放入导航栏品牌内

json 忽略标记 ("-") 不适用于嵌入式子结构

r - R 中的嵌套 for 循环有问题