使用锚点获取现有 div 的子 div 下一个没有 ID 的元素或 class 使用 JQuery

Get child div of existing div using anchors next element without ID or class using JQuery

正如您在下面看到的,$(nextDiv + ' > div').eq(i).fadeIn('slow'); 不起作用,因为它似乎格式不正确。 nextDiv 正在检查锚点下方的 div,如何获得位于其中的两个 div?

HTML:

<a href="#" id="btn2" onclick="subClick(this)">Sub Click</a>
<div>
    <div>I want this to fade in on the click</div>
    <div>Followed by this etc.</div>
</div>

Javascript:

function subClick(myAnchor)
{
    var nextDiv = $(myAnchor).next();
    function showDiv(i) {
        if (i > 2) return;
        setTimeout(function () {
            $(nextDiv + ' > div').eq(i).fadeIn('slow');
            showDiv(++i);
        }, 50);
    }
    showDiv(0);
}

您正在尝试将字符串与 jQuery 连接起来,这不会提供有效的 selector。串联将提供类似于 "[object Object] > div" 的东西,它不会 select 代码中的任何元素。

相反,在 jQuery nextDiv 对象上使用 children() 方法获取 div 个子对象。

nextDiv.children('div').eq(i).fadeIn('slow');

如果只有两个div那么你可以使用delay()方法减少代码。

function subClick(myAnchor) {
  var nextDivs = $(myAnchor).next().children();
  // if you want to do the animation after the first then
  // use the below code, where second animation initializing within 
  // the first animation success callback, which also provides a 50ms          
  // delay for second animation(avoid .delay(50) if you dont nedd that delay)
  
  //  nextDivs.eq(0).fadeIn('slow', function() {
  //    nextDivs.eq(1).delay(50).fadeIn('slow');
  //  });

  
  // in case you just want to provide a 50ms delay
  // between animation then use, your code does this
  nextDivs.eq(0).fadeIn('slow');
  nextDivs.eq(1).delay(50).fadeIn('slow');
}

var nextDiv = $(myAnchor).next(); 那么 nextDiv 是一个 object 而不是选择器。如果你想访问它的 div children 使用这个:

nextDiv.children('div').eq(i).fadeIn('slow');