简体   繁体   English

vanilla js - classList.add 不工作,但 className 工作?

[英]vanilla js - classList.add not working, but className does work?

I'm trying to rewrite/modify a navigation example from the WAI tutorials documentation ( https://www.w3.org/WAI/tutorials/menus/flyout/ ).我正在尝试重写/修改 WAI 教程文档( https://www.w3.org/WAI/tutorials/menus/flyout/ )中的导航示例。

My question only concerns the snippet of code below.我的问题只涉及下面的代码片段。 The original docs use this.className which I'm trying to change to this.classList.add , but it does nothing at all.原始文档使用this.className ,我试图将其更改为this.classList.add ,但它什么也没做。 There are no errors in the console, and console logging both navPrimaryLi and the mouseover event works fine.控制台中没有错误,并且控制台记录navPrimaryLimouseover事件都可以正常工作。

Why can I not use this.classList.add ?为什么我不能使用this.classList.add

let navPrimaryLi = document.querySelectorAll('#primary-nav li.menu-item-has-children');

Array.prototype.forEach.call(navPrimaryLi, function(el, i){
  el.addEventListener('mouseover', function(event){
    this.classList.add = 'open'; // does nothing
    // this.className = 'open'; // changes the class name to 'open'
  });
});

Many thanks!非常感谢!

Try running add instead assign尝试运行 add 而不是 assign

this.classList.add('open')

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

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