我无法删除我给容器的 class

I can't remove the class I gave to the container

我尝试将 class 添加到我单击的文本容器,然后 class 为我单击的文本分配颜色。问题是当我两次单击相同的文本时,class 不会被删除。这种情况有什么解决办法吗?

请不要更改 CLASS 所在的位置

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>

删除redclass时,检查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>

您可以使用 closest 轻松切换 class red 作为:

closest searches the DOM upwards for an element that matches the selector. 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

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>