为什么我的element.classList.add有效,但切换不起作用?

问题描述 投票:0回答:1

点击按钮后,我需要添加/删除课程。由于某些原因,classList.toggle将不起作用,但classList.add可以正常工作。

document.querySelectorAll('.view-now').forEach( function (){
    this.addEventListener('click', function(e) {
        const property = e.target.closest('.property');
        property.classList.toggle('expand');
    });
});
javascript dom
1个回答
0
投票

您能否更改this中的forEach,因为它是指文档上下文而不是特定的a标记。在原始代码中,该页面正在侦听整个页面的单击,这导致了您所面临的问题。

/**** Your JS Here ****/
//define DOM element
//this makes whatver you click dissappear both boxes
document.querySelectorAll(".view-now").forEach(function(item) {
  item.addEventListener("click", function(e) {
    const property = e.target.closest(".property");
    property.classList.toggle("expand");
  });
});

Codepen

© www.soinside.com 2019 - 2024. All rights reserved.