jQuery - 链接多个.next()方法的替代方法

时间:2015-12-07 02:26:45

标签: javascript jquery function

我有一个像这样的jQuery代码:

$(this).next().next().next().next().html('<span>anything</span>');

现在我想知道那些.next()函数还有其他选择吗? (类似于4*next()

注意: .nextUntil()对我没用,因为我没有任何线索可以在.nextUntil()中使用它。 (我的HTML结构是动态的。换句话说,它不是常数。有时候最后的元素是span,有时它是div等等......)

编辑:以下是我的HTML结构的一些示例:

例1:

<button>click it</button>
<div>div1</div>
<div>div2</div>
<span>span1</span>
<a>a1</a>              <!-- target !! and it should be <span>anything</span> -->
<div>div3</div>

例2:

<button>click it</button>
<span>span1</span>
<b>b1</b>
<span>span2</span>
<div>div1</div>       <!-- target !! and it should be <span>anything</span> -->
<div>div2</div>
<div>div3</div>

2 个答案:

答案 0 :(得分:9)

您可以合并.nextAll() / .eq()方法:

$(this).nextAll().eq(3);

作为旁注,.eq()方法接受从零开始的索引,这意味着.eq(3)将选择第四个元素。

实施例

$('div.nextAll span:first').nextAll().eq(3).addClass('selected');

$('div.multipleNext span:first').next().next().next().next().addClass('selected');
.selected {
  color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nextAll">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span>
</div>

<div class="multipleNext">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span>
</div>

或者,正如评论中所指出的,您还可以使用general sibling combinator, ~:eq()选择器的组合:

$('~:eq(3)', this);

或:

$(this).find('~:eq(3)');

实施例

$('~:eq(3)', 'div.nextAll span:first').addClass('selected');

$('div.multipleNext span:first').next().next().next().next().addClass('selected');
.selected {
  color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nextAll">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span>
</div>

<div class="multipleNext">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span>
</div>

答案 1 :(得分:2)

可以使用next siblings selector:eq()。正如@JoshCrozier所指出的,.eq():eq()是基于0的索引

$("~ :eq(3)", this)

&#13;
&#13;
$("button").click(function() {
  $("~ :eq(3)", this).html("<span>anything</span>")
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>click it</button>
<div>div1</div>
<div>div2</div>
<span>span1</span>
<a>a1</a>              <!-- target !! and it should be <span>anything</span> -->
<div>div3</div>
&#13;
&#13;
&#13;