如何用JQuery按奇偶对加载同class的<p>标签?
Hey there! Let's get your paragraph pairs fading in correctly instead of one by one. First, let's fix a quick issue in your original code, then adjust the logic to handle groups of two elements.
First: Fix the jQuery Selector
Your original code uses $("storyline") which won't find any elements—you need to add a dot (.) before the class name to target elements by class: $(".storyline").
Option 1: Load Groups with Timed Delays (Matching Your Original Timing Flow)
This approach keeps a similar delay pattern to your original code, but groups elements into pairs. Each pair fades in 1 second after the previous pair, and both elements in a pair fade in at the same time:
$(document).ready(function() { const $storylines = $(".storyline"); // Loop through elements 2 at a time for (let i = 0; i < $storylines.length; i += 2) { // Calculate delay based on the pair number (not individual element index) const pairDelay = 1000 * (i / 2); // Get the first element in the current pair const $first = $storylines.eq(i); // Get the second element (if it exists) const $second = $storylines.eq(i + 1); // Fade in both elements in the pair with the calculated delay $first.delay(pairDelay).fadeIn('slow'); if ($second.length) { $second.delay(pairDelay).fadeIn('slow'); } } });
Option 2: Load Groups with a 3-Second Display Between Pairs
If you want each pair to stay visible for 3 seconds before the next pair fades in (matching your original .delay(3000) intent), a recursive approach works better. This ensures the 3-second wait happens after the current pair finishes fading in:
$(document).ready(function() { const $storylines = $(".storyline"); let currentPairIndex = 0; function loadNextPair() { // Stop if we've gone through all elements if (currentPairIndex * 2 >= $storylines.length) return; const elementIndex = currentPairIndex * 2; const $first = $storylines.eq(elementIndex); const $second = $storylines.eq(elementIndex + 1); // Fade in the current pair $first.fadeIn('slow'); if ($second.length) { $second.fadeIn('slow'); } currentPairIndex++; // Wait 3 seconds before loading the next pair setTimeout(loadNextPair, 3000); } // Start loading the first pair loadNextPair(); });
How This Works
- Both solutions group elements into pairs:
[0,1],[2,3],[4,5], etc. - If there's an odd number of elements (like your 7th paragraph), the last element will load alone as the final "pair".
- The selector is fixed to target the
.storylineclass correctly, and we avoid using IDs as requested.
内容的提问来源于stack exchange,提问作者Nicholas Ragan

