gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:49:37 25 4
gpt4 key购买 nike

我有这样的 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>

最佳答案

您可以结合 .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>

关于javascript - jQuery - 链接多个 .next() 方法的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34125485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com