简体   繁体   English

classList.contains(“active”) 返回 false 或错误。 从不真实

[英]classList.contains(“active”) returns false OR error. never true

I'm having a strange issue here, I have an app with a div that has a click event attached to all inner elements, and when a div is clicked it adds a class "active" when I log我在这里遇到了一个奇怪的问题,我有一个带有 div 的应用程序,该应用程序的所有内部元素都附加了一个点击事件,当我点击一个 div 时,它会在我登录时添加一个“活动”类

console.log(element.classList.contains("active")); 

every element that HAS the active class errors and the ones that don't return "false"每个具有活动类错误的元素和不返回“false”的元素

EG HTML: EG HTML:

<div class="kick">
  <div class="pads kick-pad p0"></div>
  <div class="pads kick-pad p1 active"></div>
  <div class="pads kick-pad p2"></div>
  <div class="pads kick-pad p3 active"></div>
  <div class="pads kick-pad p4"></div>
  <div class="pads kick-pad p5"></div>
  <div class="pads kick-pad p6"></div>
  <div class="pads kick-pad p7"></div>
</div>

Edit: the error: "Uncaught TypeError: element.classList.contains is not a function" 2nd Edit: I should add that编辑:错误:“Uncaught TypeError: element.classList.contains is not a function”第二次编辑:我应该补充一点

console.log(element.classList); 

returns a single element with all the classes on it, including active.返回一个包含所有类的单个元素,包括活动的。 it only errors with the ".contains" method它只会在“.contains”方法中出错

3rd Edit: https://codepen.io/ruination/pen/qBZyVpQ第三次编辑: https : //codepen.io/ruination/pen/qBZyVpQ

to clarify:澄清:

  1. the elements are the correct elements and have the correct class but it doesn't return true OR false, only the error: "Uncaught TypeError: element.classList.contains is not a function"元素是正确的元素并具有正确的类,但它不返回真或假,只有错误:“未捕获的类型错误:element.classList.contains 不是函数”

  2. it DOES return false when the elements don't have the class "active" though.但是,当元素没有“活动”类时,它确实返回 false。

Judging by your code and that the unknown part is how you select the element, I assume that's where the problem is.根据您的代码以及未知部分是您如何选择元素,我认为这就是问题所在。

For example, on this page, if you open the console and select the question element and check if it has a class as such:例如,在此页面上,如果您打开控制台并选择问题元素并检查它是否具有这样的类:

document.querySelector('#question-header').classList.contains('grid');

It will return true它会返回true

And if you do:如果你这样做:

document.querySelector('#question-header').classList.contains('gri');

It will return false它会返回false

As simple as that.就如此容易。 Make sure before you check for a class, see if the element variable does have the correct element you want.确保在检查类之前,查看element变量是否包含您想要的正确元素。 Debugging before that point might also help.在此之前进行调试也可能有所帮助。

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

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