如何切换多个属性

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

我必须切换按钮和父元素(卡片)的类别

let btns = document.querySelectorAll('.btn-primary');
btns.forEach(btn => {
  btn.addEventListener('click', function(e){
    e.target.parentElement.classList.toggle('red');
    e.target.classList.toggle('green');
  });
});

但是,实际上,卡和按钮不会同时更改类别。卡变成红色,但单击另一个按钮后按钮变成绿色。

javascript html dom dom-manipulation
1个回答
0
投票

您可以稍微扩展一下单击功能,并确定所有按钮是否也应包含绿色类别

let btns = document.querySelectorAll('.btn-primary');
btns.forEach(btn => {
  btn.addEventListener('click', function(e) {
    const parentElement = e.target.parentElement;
    const element = e.target;

    for (let button of document.querySelectorAll('.btn-primary')) {
    if(button === element){
    continue
    }
      if (button.classList.contains('green')) {
        button.classList.toggle('green');
      }
    }

    element.classList.toggle('green');
    
    if([...document.querySelectorAll('.btn-primary')].some(element => element.classList.contains('green'))) {
    parentElement.classList.add('red');
    }
    else {
    parentElement.classList.remove('red');
    }
    
  });
});
.parent {
  padding: 1rem;
  border: 1px solid black;
}

.parent.red {
  border-color: red;
}

.green {
  color: green;
}

.red {
  color: red;
}
<div class="parent">
  <button class="btn-primary">Test</button>
  <button class="btn-primary">Test</button>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.