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

如何用JQuery按奇偶对加载同class的<p>标签?

Solution to Fade In

Tags in Odd-Even Pairs

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 .storyline class correctly, and we avoid using IDs as requested.

内容的提问来源于stack exchange,提问作者Nicholas Ragan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:08:20