简体   繁体   English

我无法删除我给容器的类

[英]I can't remove the class I gave to the container

I tried to add a class to the text container that I click on and then the class assigns a color to the text I click on.我尝试向我单击的文本容器添加一个类,然后该类为我单击的文本分配一种颜色。 the problem is when i click the same text twice, the class won't be removed.问题是当我单击相同的文本两次时,该类不会被删除。 Any solution for this case?这种情况有什么解决办法吗?

PLEASE DON'T CHANGE WHERE THE CLASS IS请不要改变上课地点

 const contain = document.querySelector('.contain'); const inConts = document.querySelectorAll('.in-cont'); contain.addEventListener('click', e => { for (inCont of inConts) { inCont.classList.remove('red'); } if (e.target.classList.contains('txt')) { e.target.parentElement.classList.toggle('red'); } });
 .in-cont.red .txt { color: red; }
 <div class="contain"> <div class="in-cont"> <p class="txt">Lorem ipsum dolor sit.</p> </div> <div class="in-cont"> <p class="txt">Lorem ipsum dolor sit.</p> </div> <div class="in-cont"> <p class="txt">Lorem ipsum dolor sit.</p> </div> </div>

You can easily toggle the class red using closest as:您可以使用closest方式轻松切换red类:

closest searches the DOM upwards for an element that matches the selector. closest DOM 向上搜索与选择器匹配的元素。 This search includes the element itself.此搜索包括元素本身。

element.closest(selector)

If it finds an element that matches the selector, it returns the element.如果找到与选择器匹配的元素,则返回该元素。 If it doesn't find any elements, it returns null如果没有找到任何元素,则返回null

 const contain = document.querySelector('.contain'); const inConts = document.querySelectorAll('.in-cont'); contain.addEventListener('click', e => { if (e.target.closest("div.contain")) { e.target.closest("div.in-cont").classList.toggle("red") } });
 .in-cont.red .txt { color: red; }
 <div class="contain"> <div class="in-cont"> <p class="txt">Lorem ipsum dolor sit.</p> </div> <div class="in-cont"> <p class="txt">Lorem ipsum dolor sit.</p> </div> <div class="in-cont"> <p class="txt">Lorem ipsum dolor sit.</p> </div> </div>

When removing the red class, check whether inCont contains the event target:移除red类时,检查inCont是否包含事件目标:

 const contain = document.querySelector('.contain'); const inConts = document.querySelectorAll('.in-cont'); contain.addEventListener('click', e => { for (inCont of inConts) { if (!inCont.contains(e.target)) { inCont.classList.remove('red'); } } if (e.target.classList.contains('txt')) { e.target.parentElement.classList.toggle('red'); } });
 .in-cont.red .txt { color: red; }
 <div class="contain"> <div class="in-cont"> <p class="txt">Lorem ipsum dolor sit.</p> </div> <div class="in-cont"> <p class="txt">Lorem ipsum dolor sit.</p> </div> <div class="in-cont"> <p class="txt">Lorem ipsum dolor sit.</p> </div> </div>

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

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