【问题标题】:Find next element out of parent using jQuery使用jQuery从父元素中查找下一个元素
【发布时间】:2016-03-04 08:21:26
【问题描述】:

我有以下 DOM 结构:

<label>
  <span class="tt">
    <a href="#" class="editable">Hello1</a>
    <a href="#" class="editable">Hello2</a>
    <a href="#" class="editable">Hello3</a>
    <a href="#" class="editable">Hello4</a>
  </span>
  <a href="#" class="editable">Hello5</a>
</label>

当我点击锚点Hello3 时,我需要得到Hello4 并且它工作得非常好。但是如果我点击链接Hello4,我需要得到Hello5,但我没有正确获得。

我正在使用以下代码:

$(document).on('click','.editable',function(){
  console.log($(this).nextAll('.editable').first());
});

我真正想要的是当我点击一个锚点时,在标签标签中获得下一个具有editable 类的元素。

【问题讨论】:

    标签: jquery dom nextsibling


    【解决方案1】:

    您不能使用 nextAll(),因为它基于兄弟元素,在您的情况下,所有 editable 元素都不是兄弟元素。

    您可以使用基于索引的查找来查找下一个元素,例如

    $(document).on('click', '.editable', function() {
      var $all = $('.editable');
      snippet.log($all.eq($all.index(this) + 1).text());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
    <label>
      <span class="tt">
        <a href="#" class="editable">Hello1</a>
        <a href="#" class="editable">Hello2</a>
        <a href="#" class="editable">Hello3</a>
        <a href="#" class="editable">Hello4</a>
      </span>
      <a href="#" class="editable">Hello5</a>
    </label>

    【讨论】:

      【解决方案2】:

      除了选择特定类的元素的类选择器之外,您还可以使用返回给定元素的所有同级的兄弟函数。 像这样的:

      $(document).on('click','.editable',function(){
        console.log($('.tt').siblings('.editable').first());
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-09
        • 2010-12-20
        • 2012-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-09
        • 2011-11-29
        • 1970-01-01
        相关资源
        最近更新 更多