javascript - 使用JQuery获取没有ID或类的 anchor 下一个元素的现有div的子div

标签 javascript jquery html css

正如您在下面看到的那样 $(nextDiv + ' > div').eq(i).fadeIn('slow'); 不起作用,因为它似乎格式错误。 nextDiv 正在检查 anchor 下方的 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 连接一个字符串,这不会提供有效的选择器。连接将提供类似 [object Object] > div" 的东西,它不会选择代码中的任何元素。

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

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');
}

关于javascript - 使用JQuery获取没有ID或类的 anchor 下一个元素的现有div的子div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41923041/

相关文章:

javascript - react native + 终极版 : How to render <ListView/> upon clicking a button?

javascript - 如何在 Angular ui-router 中的 anchor 单击中启用默认事件

javascript - 使用 Underscore.js 在嵌套集合中查找对象

html - 将html转换为pdf时出现wkhtmltopdf分页问题

html - 减少导航 Bootstrap 中的间距

javascript - 在学习 AngularJS 之前,我应该了解 JavaScript 中的哪些内容?

JavaScript 通过正则表达式拆分字符串

c# - 使文本字段可见但不可编辑

javascript - 哈希表是如何在 JavaScript 中实现的

javascript - 跨域 Javascript 书签