jQuery Next/NextAll/Next直到计数限制 [英] Jquery Next/NextAll/NextUntil with count limit

查看:161
本文介绍了jQuery Next/NextAll/Next直到计数限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道该答案,真让我很烦,我认为这很简单.我想将选定元素中的下一个和上一个元素限制为一个上限(例如2).这是一个示例:

Its really annoying me that I don't know the answer to this, I thought it would be simple. I want to get the next and previous elements from a selected element to a limit (say 2). Here is an example:

<ul>
<li>link 1</li>
<li>link 2</li>
<li>link 3</li>
<li>link 4</li>
<li class='active'>link 1</li>
<li>link 6</li>
<li>link 7</li>
<li>link 8</li>
<li>link 9</li>
</ul>

所以我想选择活动的li之前的两个元素和之后的2个元素.我尝试做类似的事情: $('li.active').nextAll(':eq(2)');,然后使用prevAll将其添加到同一个元素中,但是它选择了一个元素2个兄弟姐妹而不是整个组.

So I want to select two elements before and 2 elements after the active li. I have tried doing something like: $('li.active').nextAll(':eq(2)'); and then adding it to the same using prevAll but it selects one element 2 siblings away instead of the whole group.

一定有一种我想念的简单方法,有什么建议吗?

There must be an easy way of doing this that I have missed, any suggestions?

我无法编辑HTML,它是动态生成的.

N.B. I cant edit the HTML, it is generated dynamically.

推荐答案

(至少)有两种方法可以解决此问题.您可以链接 prevAll() slice(),然后使用 add()组合这两个集合:

There are (at least) two approaches to this problem. You can chain prevAll() and nextAll() into slice(), then use add() to combine the two sets:

var $active = $("li.active");
var $around = $active.prevAll().slice(0, 2)
                     .add($active.nextAll().slice(0, 2));

或者您可以获取活动元素的 index(),请使用slice()获取围绕该索引的兄弟姐妹,然后使用 not():

Or you can fetch the index() of the active element, use slice() to get siblings around that index, then filter the active element out with not():

var $active = $("li.active");
var activeIndex = $active.index();
var $around = $active.siblings().addBack()
                     .slice(Math.max(0, activeIndex - 2), activeIndex + 3)
                     .not($active);

这篇关于jQuery Next/NextAll/Next直到计数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆