我有以下html
和JavaScript
将名为is-active
的活动类添加到菜单项onClick
。当您单击另一个项目时,它将从上一个项目中删除并添加到当前项目中。我从 W3Schools 获得的代码如下。我想知道是否有更好,更现代的JavaScript编写方式。 (NO jQuery)只有简单的vanilla JavaScript
HTML:
<div class="our-clients__categories">
<a href="#technology" class="our-clients__categories--category is-active"><h4>Technology</h4></a>
<a href="#retail" class="our-clients__categories--category"><h4>Retail</h4></a>
<a href="#finance" class="our-clients__categories--category"><h4>Finance</h4></a>
<a href="#consumer" class="our-clients__categories--category"><h4>Consumer</h4></a>
<a href="#hospitality" class="our-clients__categories--category"><h4>Hospitality</h4></a>
</div>
JavaScript的:
export default function () {
const clientCategoryButtons = document.querySelectorAll('.our-clients__categories--category')
clientCategoryButtons.forEach((categorybtn) => {
categorybtn.addEventListener('click', function (e) {
e.preventDefault()
const current = document.getElementsByClassName('is-active')
current[0].className = current[0].className.replace('is-active', '')
this.className += ' is-active'
})
})
}
感谢任何和所有帮助! :)