2

我有以下 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当我点击一个锚点时,在标签标签中获得下一个具有 class of 的元素。

4

2 回答 2

5

您不能使用 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>

于 2016-03-04T08:24:46.327 回答
0

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

$(document).on('click','.editable',function(){
  console.log($('.tt').siblings('.editable').first());
});
于 2016-03-04T08:35:49.843 回答