使用jQuery的.closest().next(.class)无法选中目标div的问题排查
Hey there! Let's break down why only your first choice button works, and fix the rest so each button correctly targets its corresponding text section.
The Root Problem
Your current use of .next(.class) is the culprit here. The .next() method only looks at the immediately following sibling element of your .text-section:
- For
c-btn-1, the.c-1div is directly after the initial.text-section, so.next(".c-1")finds it perfectly. - For
c-btn-2and beyond, the target.c-2/.c-3/.c-4divs aren't the immediate next sibling (the immediate next is.c-1), so.next()can't locate them. That's why those buttons fail to trigger the right action.
The Solution: Use nextAll() + first()
Instead of .next(), use .nextAll(selector) to grab all sibling elements that come after your .text-section and match the selector, then chain .first() to pick the very first one (which is exactly the next target you need in your HTML structure).
Step 1: Simplify Your Code (Avoid Repetition)
First, let's clean up your duplicated jQuery code. Add a data-target attribute to each choice button that points to its corresponding section class—this makes your code scalable and easier to maintain.
Updated HTML for buttons:
<ul class="choice-display" id="choice-display-1"> <li class="c-btn btn sth-btn c-btn-1" data-target=".c-1">Choice 1</li> <li class="c-btn btn pre-btn c-btn-2" data-target=".c-2">Choice 2</li> <!-- Repeat this pattern for c-btn-3, c-btn-4, etc. --> </ul>
Step 2: Updated jQuery Code
Replace all your individual button click handlers with this single, reusable function:
// Handle all choice buttons $(".c-btn").click(function() { // Get the target selector from the button's data attribute const targetClass = $(this).data("target"); // Find the FIRST matching sibling section after the current text-section const targetSection = $(this).closest(".text-section").nextAll(targetClass).first(); // Show and activate the target section targetSection.show("medium").addClass("active"); }); // Handle the cp-btn separately (since it targets a different class) $(".cp-btn").click(function() { const targetSection = $(this).closest(".text-section").nextAll(".choice-plus").first(); targetSection.show("medium").addClass("active"); });
Why This Works
.nextAll(targetClass)searches all sibling elements that come after the parent.text-sectionand match the target selector (like.c-2)..first()ensures we only select the first occurrence of that target class, which is exactly the next section you want to reveal in your story flow.
This approach fixes your selector issue and makes your code much cleaner—no more repeating the same logic for every single button!
内容的提问来源于stack exchange,提问作者Pontus Holmqvist

