jQuery FAQ手风琴实现单次展开:如何用父子选择器解决批量展开问题
Absolutely! The problem you're facing is that your current click handler targets every .sub-slide element on the page whenever any .main-slide-plus button is clicked. We can use jQuery's traversal methods (like parent()/closest() and next()) to target only the specific answer section tied to the button you clicked—no need to overhaul your HTML structure at all.
Let's Break Down the Solution
First, let's look at your HTML structure: each FAQ "question" lives in a .main-slide container, and immediately after it sits the matching .sub-slide answer. So when you click the .main-slide-plus inside a .main-slide, we just need to traverse up to that parent container, then select the .sub-slide right after it.
Modified jQuery Code
Here's the fixed version using parent() and next():
$(".main-slide-plus").click(function () { // Traverse up to the parent .main-slide of the clicked button // Then target the immediate next .sub-slide element $(this).parent(".main-slide").next(".sub-slide").slideToggle(500); });
Bonus: More Robust Traversal with closest()
If your HTML ever gets nested deeper (e.g., adding extra elements inside .main-slide), closest() is more reliable than parent()—it finds the nearest ancestor matching the selector, not just the direct parent:
$(".main-slide-plus").click(function () { $(this).closest(".main-slide").next(".sub-slide").slideToggle(500); });
Optional: Close Other Answers When Opening a New One
If you want only one answer open at a time (closing any previously expanded answers when clicking a new button), add this extra step:
$(".main-slide-plus").click(function () { const targetSlide = $(this).closest(".main-slide").next(".sub-slide"); // Slide up all .sub-slide elements except the target one $(".sub-slide").not(targetSlide).slideUp(500); // Toggle the target answer targetSlide.slideToggle(500); });
Quick HTML Fix
Note: Your original HTML has an extra closing </div> at the end—make sure to remove that to keep the structure valid:
<div class="main-slide"> <div class="main-slide-title"> <p>One-time Close Purchase/Construction Loans</p> </div> <div class="main-slide-plus"> <p>+</p> </div> </div> <div class="sub-slide default-hidden"> <ul> <li>Finance the construction</li> <li>Purchase of lot</li> <li>Permanent loan</li> <li>FHA, and VA are available</li> </ul> </div> <!-- Removed the extra </div> here -->
That's it! Now clicking each "+" button will only toggle its corresponding answer section, exactly what you wanted.
内容的提问来源于stack exchange,提问作者shMattyP93

