简体   繁体   English

addEventListener单击仅一次可用于类更改

[英]addEventListener click only works once for class change

I may be approaching this completely wrong- it has to be done in vanilla JS. 我可能正在处理完全错误的问题-必须在香草JS中完成。

I have DOM elements that I try to hide and show on clicks. 我有一些DOM元素,它们会在点击时隐藏并显示。 I had this similar setup working for collapsible menu's and it worked fine. 我有类似的设置适用于可折叠菜单,并且工作正常。 Not sure what I'm doing wrong here. 不知道我在做什么错。

windows.onload = function() {
  features.addEventListener('click',function(){
      render(0); 
  })
  specs.addEventListener('click',function(){
      render(1); 
  })
  function render(which) {
    if (0) {
        console.log('0 clicked')
        features.classList.add('active');
        specs.classList.remove('active');
        renderFeatures.classList.remove('hidden');
        renderSpecs.classList.add('hidden');
    } else if (1) {
        console.log('1 clicked')
        features.classList.remove('active');
        specs.classList.add('active');
        renderFeatures.classList.add('hidden');
        renderSpecs.classList.remove('hidden');
    } 
}

I'm trying to add an active class and remove the hidden class on clicking both elements. 我试图在单击两个元素时添加一个活动类并删除隐藏的类。 It works when I click one, but then after that, it doesn't work anymore. 当我单击一个时,它可以工作,但是此后,它不再工作。

if (0) will always evaluate to false . if (0)将始终为false You have to use the value of which variable that you're not doing anywhere. 你必须使用的值, which的变量,你没有做任何地方。

function render(which) {
  if (which === 0) {
    console.log('0 clicked')
    features.classList.add('active');
    specs.classList.remove('active');
    renderFeatures.classList.remove('hidden');
    renderSpecs.classList.add('hidden');
  } else if (which === 1) {
    console.log('1 clicked')
    features.classList.remove('active');
    specs.classList.add('active');
    renderFeatures.classList.add('hidden');
    renderSpecs.classList.remove('hidden');
  } 
}

windows.onload = function() {
  features.addEventListener('click',function(){
      render(0); 
  })
  specs.addEventListener('click',function(){
      render(1); 
  })
}

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

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