简体   繁体   English

如何在使用 vanilla JS 的下一次单击时在单击事件中添加和删除类?

[英]How to add and remove classes inside a click event on the next click with vanilla JS?

When I click the event listener for the second time, new classes are added based on the condition, but the previous classes are not removed and/or reset.当我第二次单击事件侦听器时,会根据条件添加新类,但不会删除和/或重置以前的类。

Enter a year older than 1980 and see the result.输入早于 1980 年的年份并查看结果。 Click 'Get Started' again and enter a year newer than 1980 (don't refresh the page) and the class attached to the new result doesn't change.再次单击“开始”并输入比 1980 年新的年份(不要刷新页面),新结果中附加的 class 不会更改。

 fakeEvent.addEventListener('click', function() { let birthYear = prompt("What year were you born", ""); let currentYear = new Date().getFullYear(); let age = currentYear - birthYear; if (age <= 40) { result.innerHTML = `You entered ${age} years old.`; result.classList.add('black'); } else { result.innerHTML = `You entered ${age} years old.`; result.classList.add('green'); } })
 .black { background: black; color: white; }.green {background: green; color: yellow; } h4 { margin-top: 3rem; }
 <div class="container"> <button type="button" id="fakeEvent">Get Started</button> <hr /> <div id="result"></div> <h4>Enter a year older than 1980 and see the result. Click 'Get Started' again and enter a year newer than 1980 (don't refresh the page) and the class attached to the new result doesn't change.</h4> </div>

You can simply clear the classList out before making the change您可以在进行更改之前简单地清除 classList

  result.classList.remove('black', 'green');

 fakeEvent.addEventListener('click', function() { let birthYear = prompt("What year were you born", ""); let currentYear = new Date().getFullYear(); let age = currentYear - birthYear; result.classList.remove('black', 'green'); if (age <= 40) { result.innerHTML = `You entered ${age} years old.`; result.classList.add('black'); } else { result.innerHTML = `You entered ${age} years old.`; result.classList.add('green'); } })
 .black { background: black; color: white; }.green {background: green; color: yellow; } h4 { margin-top: 3rem; }
 <div class="container"> <button type="button" id="fakeEvent">Get Started</button> <hr /> <div id="result"></div> <h4>Enter a year older than 1980 and see the result. Enter a year newer than 1980 and the class attached to the new result doesn't change.</h4> </div>

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

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