将 .active class 设置为动态创建的 link JS

Setting up an .active class to a dynamically created link JS

几周前我构建了一个导航栏,然后才意识到我没有在上面设置 .active class。现在,我在 JS 中动态构建了导航栏和 links,现在想根据 CSS.

给激活的那个

这是我在 JS 中构建导航栏的方式:

let womensNav = document.createElement("ul");
womensNav.classList.add("womensNav");

const el1 = document.createElement("li");
el1.innerHTML = "<a>Jeans</a>";
el1.addEventListener("click", (e) => {
      document.location.href =
        "https://www.martadolska.com/product-category/women/womens-jeans";
});

womensNav.appendChild(el1);
document.querySelector(".ast-woocommerce-container").appendChild(womensNav);

我有不止一个 link,但为此我不需要全部展示。所以现在的目标是构建一个通用函数,为导航栏中的活动元素提供相应的 class.

document.querySelectorAll("#womensNav li").forEach(function (ele) {
      ele.addEventListener("click", function (e) {
        e.preventDefault();
        document
          .querySelectorAll("#womensNav li a.active")
          .forEach((ele) => ele.classList.remove("active"));
        ele.parentNode.classList.toggle("active");
      });
    });

这就是我的 CSS 的样子:

.womensNav li a:hover {
  color: var(--main-text-color);
  text-decoration: line-through darkred solid;
}
.womensNav li a::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 7px;
  left: 0;
  background-color: #b22222;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}
.womensNav li a:hover::before {
  visibility: visible;
  transform: scaleX(1);
}
.womensNav li a:active::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 10px;
  left: 0;
  background-color: #b22222;
}

// up until this point everything works
.active {
  text-decoration: line-through darkred solid;
}

我猜 JS 代码的第二个片段中有一些东西 missing/not 完全正确,因为当我的 link 处于活动状态时什么也没有发生。我得到了我想要得到的动画,但是一旦用户被重定向到那个特定的 link,它就会消失,所以你不知道你在哪个子页面上。

这是错误的

ele.parentNode.classList.toggle("active");

“ele”是 <li>,您正在通过父节点将“活动”class 添加到 <ul>,使用来自的“e”事件可能更好单击并使用 e.target 然后尝试在 <a> 上设置活动 class 或使用 childNode/children 获取您的 <a>