首页 > 解决方案 > 在动态菜单上实现寻路

问题描述

我需要帮助做作业。我需要通过在动态生成的导航中突出显示活动菜单项来创建 Wayfinder。当单击按钮更改菜单项时,我的代码没有响应。这是我渲染的 HTML 和 JavaScript 代码。

var urlLink = "http://localhost/acme/products/?action=category&categoryName=Rocket";
var path = urlLink.split("=").pop();
console.log(path);

liContainer = document.getElementById("navMenu");
const navAnchor = liContainer.getElementsByClassName('mainMenu');
/*
navAnchor.forEach(anchor => {
  anchor.addEventListener('click', addActive);
});
*/
for (var i = 0; i < navAnchor.length; i++) {
  navAnchor[i].addEventListener("click", addActive);
}


function addActive(e) {
  var liAnchor = liContainer.target.tagName("a").getAttribute("href");
  if (liAnchor.split("=").pop() === path) {
    const current = document.querySelector('li.active');
    current.className = current.className.replace(" active", "");
    e.target.className += " active";
  }
}
.active {
  background-color: red;
  color: white;
  padding: 10px
}
<ul id="navMenu">
  <li class="mainMenu active"><a href="/acme/" title="View the Acme home page">Home</a></li>
  <li class="mainMenu"><a href="/acme/products/?action=category&amp;categoryName=Cannon" title="View our Cannon product line">Cannon</a></li>
  <li class="mainMenu"><a href="/acme/products/?action=category&amp;categoryName=Explosive" title="View our Explosive product line">Explosive</a></li>
  <li class="mainMenu"><a href="/acme/products/?action=category&amp;categoryName=Misc" title="View our Misc product line">Misc</a></li>
  <li class="mainMenu"><a href="/acme/products/?action=category&amp;categoryName=Rocket" title="View our Rocket product line">Rocket</a></li>
  <li class="mainMenu"><a href="/acme/products/?action=category&amp;categoryName=Trap" title="View our Trap product line">Trap</a></li>
</ul>

我希望突出显示活动菜单。

标签: javascripthtml

解决方案


我使用以下代码解决了我自己的问题:

var path = window.location.href.split("=").pop();

var liContainer = document.getElementById("navMenu");
const navAnchor = liContainer.getElementsByClassName('mainMenu');

for (var i = 0; i < navAnchor.length; i++) {  
  var liAnchor = navAnchor[i].getElementsByTagName("a");
  for (var j = 0; j < liAnchor.length; j++) {
    linkPath = liAnchor[j].getAttribute("href").split("=").pop();
    if (linkPath === path) {
      var current = document.getElementsByClassName("active");
      current[0].className = current[0].className.replace(" active", "");
      navAnchor[i].className += " active";
    } 
  }
}


推荐阅读