jQuery向后切片或选择前5个同级

jQuery slice backwards or select previous 5 siblings

本文关键字:5个 选择 切片 jQuery      更新时间:2023-09-26

我循环遍历一系列div,因此使用slice()方法一次只出现5个div。在每4个项目之后,有一个省略号(…)链接,直接将用户引导到下一组5个项目。下面是显示所有内容而不是只有5条的效果,以防你感到困惑。
& lt;12 3 4…5 6 7 8…9 10 11 12…13 14 15 16>

当用户单击后退箭头时,我希望显示前5个div。例如,如果它们位于第二组5 (div 5, 6, 7, 8,…),则单击后退箭头将隐藏它们并显示前5 (div 1, 2, 3, 4,…)。我不认为slice()向后工作,而prev()不会工作,因为我不知道选择前5个兄弟姐妹的方法。n -child也不能工作,因为我想选择前5个,而不仅仅是:n -child(5n)。

有什么想法吗?我难住了。我不是一个jQuery高手,但我想说我目前的技能水平高于初学者。我可能让功能变得比它需要的更复杂。我做了一个小提琴,展示我已经完成了什么。
https://jsfiddle.net/nehLuj98/

$(".btn-nav").slice(0,5).show();
$(".btn-ellipsis").each(function(){
    var goNum = $(this).prev(".btn-num");
    var num = Number(goNum.attr("id"));
    var currentNum = $(this).find(".current");
    $(this).click(function(){
        $(this).hide();
        $(".btn-num").hide().slice(num,(num+4)).show().next(".btn-ellipsis").show();
        $(this).next(".current").removeClass("current");
        $(".btn-num").hide().slice(num,(num+4)).show().next(".btn-ellipsis").show();
        goNum.add("#"+(num+1)+"").addClass("current");
    });
    $(".btn-prev").click(function(){
        //Here's where I'd like to add the functionality to show the previous 5 items
        //$(".btn-nav").add(".btn-ellipsis").hide();
    });
});

我使用的是AngularJS,所以这些数字是基于。json文件动态创建的。不知道这是否相关。每隔4个编号的链接后插入省略号链接,因为链接的数量可以非常多。为了简单起见,我只是将它添加到html中。

TL;博士
是否有一种方法使用jQuery的slice()方法向后或选择前5兄弟姐妹使用不同的方法?

根据您当前的代码,您可以这样做:

$(".btn-prev").click(function(){
    if ($('.current').attr('id') === '1' || $('.current').attr('id') === '4')
    return;
  var currentElip = $('.btn-ellipsis:visible');
    if (!currentElip.length)
    currentElip = $('.btn-next');
  else
    currentElip.hide();
  var goNum = currentElip.prevAll('.btn-ellipsis').prev(".btn-num");
  var num = Number(goNum.attr("id"));
  $(".btn-num").hide().slice(num-4,(num)).show().next(".btn-ellipsis").show();
    $(".current").removeClass("current");
    $("#"+(num)).addClass("current");
});

下面是一些注释:

https://jsfiddle.net/nehLuj98/10/