Rest.next()?我的点击功能添加'.活动'两次

Rest .next()? My click function adding '.active' twice?

本文关键字:添加 两次 活动 功能 next 我的 Rest      更新时间:2023-09-26

如果你看看这个小提琴,它看起来会很好,但如果你点击下一个,向下移动2到3次,然后点击"存储器";(在顶部导航中)它将.active带回第一个.item

然后,如果您再次单击"下一步",它将继续转到我们中断的上一个元素的下一个元素。

我正在尝试重置它,并在点击顶部导航后根据我们的位置继续。

错误的jQuery:*两个点击功能都添加了活动*

var  items = $('.item'), 
     currentItem = items.filter('.active'), 
     last = items.last();    
 $("#next-button").on('click', function () {
     currentItem.removeClass('active');
     var nextItem = currentItem.next();
    if (nextItem.length) {
        currentItem = nextItem.addClass('active');
      if (currentItem.is(last)) {
         $('#slide-buttons').addClass('red');
      }
    }
    
    var items = $('.item');
      $(".breadcrumb-cell .breadcrumb").click(function () {
       var theID  = $(this).data("id");
items.filter(function() {
    return $(this).data('category') === theID;
}).addClass('active');
});
 });  

Fiddle

我在谷歌上搜索了";如何重置.next()jquery;但什么都找不到,不确定这样做是否正确?

您遇到的问题是,当您单击面包屑时,currentItem没有得到更新。

我做了很多改变,主要是"精简"。我删除了您的全局变量,并将当前项改为基于active类。检查:http://jsfiddle.net/kQabJ/17/

$("#next-button").on('click', function () {
    var nextItem = $('.active').removeClass('active').next();
    if (!nextItem.length) {
        nextItem = $('.item').first();
    }
    nextItem.addClass('active');
});
$(".breadcrumb-cell .breadcrumb").on('click', function () {
    $('.active').removeClass('active');
    var theID = $(this).data("id");
    $("#" + theID).addClass('active');
});

请注意,我还修改了您的DOM,以便在用户单击面包屑时更容易地选择项目。这种变化是在.item上使用ID而不是数据。通过这种方式,您可以执行$("#" + theID),而不是基于数据进行筛选。

由于这些东西是唯一标识.item元素本身的,因此无论如何都可以使用id,但如果不是这样,则可以随时更改该部分。

您只需要更新currentItem,请参阅http://jsfiddle.net/kQabJ/13/

$(".breadcrumb-cell .breadcrumb").on('click', function () {
     items.removeClass('active');       
     var theID  = $(this).data("id");
     items.filter(function() {
     return $(this).data('category') === theID;
    }).addClass('active');
       currentItem = items.filter('.active');
    });

试试这个代码您没有更新导致问题的currentItem

var items = $('.item'),
    currentItem = items.filter('.active'),
    last = items.last();
$("#next-button").on('click', function () {
    currentItem = items.filter('.active');
    var nextItem = currentItem.next();
    currentItem.next().length > 0 ? currentItem.next().addClass('active')
                                   : items.first().addClass('active');
    currentItem.removeClass('active');
});

$(".breadcrumb-cell .breadcrumb").on('click', function () {
    items.removeClass('active');
    var theID = $(this).data("id");
    items.filter(function () {
        return $(this).data('category') === theID;
    }).addClass('active');
});

检查Fiddle