简体   繁体   English

为什么删除 class 在 javascript 中不起作用?

[英]why remove class not working in javascript?

I have tried this before and it worked well but here i dont know...我以前试过这个,效果很好,但在这里我不知道......

<div onclick="choose(this)">
     <div class="choose">
          <button><a>click</a></button>
     </div>
</div>

my JavaScript:我的 JavaScript:

function choose(obj) {
  obj = obj || document.activeElement;
  var res_item = obj.querySelector(".choose");
  res_item.classList.add("choosed_item");
  var close = obj.querySelector(".choose button a");
  close.addEventListener("click", function closemodal() {
    if (res_item.classList.contains("choosed_item")) {
      res_item.classList.remove("choosed_item");
    }
  });
}

choose and choosed_item have custom style choosechoosed_item有自定义样式

This is strange, but if i change remove to add and choose another class it works well !这很奇怪,但是如果我将remove更改为add并选择另一个 class 效果很好!

The event is not updated because its child of onclick function.该事件未更新,因为它是 onclick function 的子级。 Thats why I integrated an interval.这就是为什么我整合了一个区间。 That will help to update the eventlistener:这将有助于更新事件监听器:

function choose(obj) {
    obj = obj || document.activeElement;
    var interval;
    var res_item = obj.querySelector(".choose");
    res_item.classList.add("choosed_item");
    var close = obj.querySelector(".choose button a");
    close.addEventListener("click", function closemodal() {
      if (res_item.classList.contains("choosed_item")) {
        interval = setInterval(function () {
          res_item.classList.remove("choosed_item");
          stopInterval();
        }, 0);
        function stopInterval() {
          clearInterval(interval);
        }
      }
    });
  }

Hope I could help!希望我能帮上忙!

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

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