Jquery Next/NextAll/NextUntil with count limit

前端 未结 2 1623
一整个雨季
一整个雨季 2021-01-05 16:44

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 (

相关标签:
2条回答
  • 2021-01-05 17:28

    You can use nextAll and prevAll combined with the less-than :lt(index) selector
    (in your case :lt(2))

    var current = $('.active'),
        next = current.nextAll(':lt(2)'),
        prev = current.prevAll(':lt(2)'),
        all = current.add(next).add(prev);
    
    0 讨论(0)
  • 2021-01-05 17:39

    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));
    

    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);
    
    0 讨论(0)
提交回复
热议问题