jQuery实现点击按钮变色:多面板各保留一个选中按钮
Got it, let's sort this out! The problem with the original code is that it targets all buttons on the page when you click one, which wipes out selections in every panel. Instead, we need to limit our changes to only the buttons inside the same panel as the clicked button. Here's how to do it:
Step 1: Target the Right Scope
We'll use jQuery's traversal methods to narrow down our action to the current panel. Assuming your panels share a class like .panel and your buttons use .btn with an .active class for the selected state, here's the code:
$(".panel .btn").click(function() { // 1. Find the closest parent panel of the clicked button const currentPanel = $(this).closest(".panel"); // 2. Remove the active class from ALL buttons in this panel currentPanel.find(".btn").removeClass("active"); // 3. Add the active class to the clicked button $(this).addClass("active"); });
How It Works
$(this).closest(".panel"): This grabs the nearest parent element with the.panelclass, ensuring we only work within the panel that contains the clicked button.currentPanel.find(".btn"): We then search only inside that panel for all buttons, so we don't touch buttons in other panels.- Removing
.activefrom those panel buttons and adding it to the clicked one keeps each panel's selection independent.
Example HTML Structure
To make this concrete, here's what your markup might look like (adjust class names to match your project):
<div class="panel"> <h4>Panel 1 - Preferences</h4> <button class="btn active">Light Mode</button> <button class="btn">Dark Mode</button> <button class="btn">System Default</button> </div> <div class="panel"> <h4>Panel 2 - Notifications</h4> <button class="btn">Email</button> <button class="btn active">Push</button> <button class="btn">SMS</button> </div>
Customization Tip
If your panels use a different class (like .card instead of .panel) or buttons use a unique class, just swap out the selectors in the jQuery code to match your actual HTML. This approach keeps each panel's button group isolated, so selections in one don't interfere with another.
内容的提问来源于stack exchange,提问作者user2915853

