繁体   English   中英

如何从单击的所有li元素中删除活动类?

[英]How to remove active class from all li elements except one that clicked?

它不会让我在脑海中完成滑块。 而且我还要注意不要使用JQuery。 仅适用于JavaScript。 我尝试了很多方法,但是没有生效。

 var ul = document.querySelector('ul'); var dots = []; for (var i = 0; i < 5; i++) { var dot = document.createElement('li'); dots.push(dot); ul.appendChild(dot); } dots[2].setAttribute('class', 'active'); 
 li { width: 20px; height: 20px; background-color: lightgrey; text-decoration: none; display: inline-block; border-radius: 100%; margin-right: 15px; } .active { background-color: grey; } 
 <ul></ul> 

这是JSFiddle链接: https ://jsfiddle.net/heybetov1998/camuyve2/4/

这是一个将为您完成的事件处理程序。

function handler(event) {
  for (const li of document.querySelectorAll("li.active")) {
    li.classList.remove("active");
  }
  event.currentTarget.classList.add("active");
}

我将留给您设置事件处理程序,并根据需要弄清楚旧版浏览器的支持。

您可以在点上连接事件处理程序。 在事件处理程序中, this将引用附加处理程序的元素。 然后,您可以从所有其他班级中删除该班级:

 var ul = document.querySelector('ul'); var dots = []; for (var i = 0; i < 5; i++) { var dot = document.createElement('li'); dot.addEventListener("click", clickHandler); // ** Hook up the handler dots.push(dot); ul.appendChild(dot); } dots[2].setAttribute('class', 'active'); // Here's the handler function clickHandler() { var dots = document.querySelectorAll("li"); for (var n = 0; n < dots.length; ++n) { if (dots[n] !== this) { dots[n].className = ""; } } this.className = "active"; } 
 li { width: 20px; height: 20px; background-color: lightgrey; text-decoration: none; display: inline-block; border-radius: 100%; margin-right: 15px; } .active { background-color: grey; } 
 <ul></ul> 

如果您需要支持没有addEventListener过时浏览器,则此答案具有执行此功能的功能。

那是最小变化的版本。 但是我要进行一些更改:

  • 不要使用setAttribute设置class属性。 它在非常老的IE版本上失败,但更重要的是,它完全替换了元素上的类。 看一下classList

  • 上面的示例将事件处理程序连接到每个点,但是如果您有很多点,或者动态添加/删除它们,则最好通过将事件处理程序连接到点容器上来使用事件委托 ,使用e.target确定单击了哪个点。

使用addEventListener将侦听器分配给您要添加的li元素的click事件。

在侦听器函数中,您可以删除所有li元素的活动类,然后仅将其添加到使用this元素引用的单击对象中。

使用元素的classList属性从元素中添加/删除活动类。

 var ul = document.querySelector('ul'); var dots = []; function dotClicked() { dots.forEach(function(li) { li.classList.remove("active"); }); this.classList.add("active"); } for (var i = 0; i < 5; i++) { var dot = document.createElement('li'); dot.addEventListener("click", dotClicked); dots.push(dot); ul.appendChild(dot); } 
 li { width: 20px; height: 20px; background-color: lightgrey; text-decoration: none; display: inline-block; border-radius: 100%; margin-right: 15px; } .active { background-color: grey; } 
 <ul></ul> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM