You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为按钮列表添加active类?求点击激活的JavaScript代码

Solution to Add Active Class to Filter Buttons on Click

Got it, here's a couple of solid solutions to handle adding the active class to your filter buttons when clicked—ensuring only one button is active at any time:

Vanilla JavaScript (No Libraries Needed)

This approach uses plain JavaScript, so you don't need to rely on jQuery or other frameworks:

// Grab all filter button elements
const filterButtons = document.querySelectorAll('.filter-button');

// Attach click event to each button
filterButtons.forEach(button => {
  button.addEventListener('click', () => {
    // First, remove the active class from every button
    filterButtons.forEach(btn => btn.classList.remove('active'));
    // Then add the active class to the button that was clicked
    button.classList.add('active');
  });
});

Quick Notes:

  • Don't forget to add the active class to your default button (like the "All" button) in your HTML so it's active when the page loads:
    <button class="filter-button btn active" data-filter="all"><span class="caps">A</span>ll</button>
    
  • Make sure this script runs after the DOM is loaded—you can either put it at the end of your <body> tag, or wrap it in a DOMContentLoaded event listener.

jQuery Alternative (If You're Using jQuery)

If your project already uses jQuery, this shorter version works great:

// When any filter button is clicked
$('.filter-button').click(function() {
  // Remove active class from all filter buttons
  $('.filter-button').removeClass('active');
  // Add active class to the clicked button
  $(this).addClass('active');
});

Either solution will handle the active state switching smoothly for your button group.

内容的提问来源于stack exchange,提问作者teshu katepalli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:57:31