javascript - 在动态菜单上实现寻路
问题描述
我需要帮助做作业。我需要通过在动态生成的导航中突出显示活动菜单项来创建 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&categoryName=Cannon" title="View our Cannon product line">Cannon</a></li>
<li class="mainMenu"><a href="/acme/products/?action=category&categoryName=Explosive" title="View our Explosive product line">Explosive</a></li>
<li class="mainMenu"><a href="/acme/products/?action=category&categoryName=Misc" title="View our Misc product line">Misc</a></li>
<li class="mainMenu"><a href="/acme/products/?action=category&categoryName=Rocket" title="View our Rocket product line">Rocket</a></li>
<li class="mainMenu"><a href="/acme/products/?action=category&categoryName=Trap" title="View our Trap product line">Trap</a></li>
</ul>
我希望突出显示活动菜单。
解决方案
我使用以下代码解决了我自己的问题:
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";
}
}
}
推荐阅读
- amazon-web-services - docker 最适合生产环境吗?
- amazon-web-services - AWS ECR 使用 podman 登录
- javascript - 修改多维数组的一个索引会导致所有其他子数组发生变异?
- r - 尝试使用 R 中的 for 循环从多个网页中抓取表格
- rundeck - 如何将脚本从 Rundeck 服务器复制到全新的 Windows Server
- python - 来自 lambda 的 Slack 通知不会破坏换行符中的消息
- windows - 从 pip3 安装包
- histogram - 一个变量的值与另一个变量的唯一值的直方图
- r - 更改多个观察的日期年份
- json - 使用 Asp.Net Core MVC 和 FullCalendar 显示 SQL 表的内容