猿问

在动态菜单上实现寻路

我需要帮助做作业。我需要通过在动态生成的导航中突出显示活动菜单项来创建 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>


慕桂英3389331
浏览 100回答 1
1回答

沧海一幻觉

我使用以下代码解决了我自己的问题: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++) {&nbsp;&nbsp;&nbsp; var liAnchor = navAnchor[i].getElementsByTagName("a");&nbsp; for (var j = 0; j < liAnchor.length; j++) {&nbsp; &nbsp; linkPath = liAnchor[j].getAttribute("href").split("=").pop();&nbsp; &nbsp; if (linkPath === path) {&nbsp; &nbsp; &nbsp; var current = document.getElementsByClassName("active");&nbsp; &nbsp; &nbsp; current[0].className = current[0].className.replace(" active", "");&nbsp; &nbsp; &nbsp; navAnchor[i].className += " active";&nbsp; &nbsp; }&nbsp;&nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答