9

私はそれが非常に単純であることを知っていますが.next().last()ちょっと混乱しています。私はちょっと混乱しています。

私が本質的にやろうとしているのは、次の要素がリストの最後の要素であるときにクラスを追加することです。

フィドル

私の現在のコードでは、最後の要素が表示された後、最初に戻ったときにクラスを追加します。

jQuery: きっと関係があると思います.length

$("#next-button").on('click', function () {
    var nextItem  = $('.active').removeClass('active').next(),
        breadItem = $('.clickable').next();

    if (!nextItem.length) {
        nextItem = $('.item').first();

        //Here I try to add class ".last" to the last ".item" element
        $('.item').last().addClass('last');
    }
    nextItem.addClass('active');
    breadItem.addClass('clickable');  
});

これにより、最後の要素をクリックして最初の要素に戻ると、クラスが追加されます。

また、ボーナスの質問については.clickable、ブレッドクラムにクラスを追加すると、最初のクラスだけが正しいdata-idチェックに移動する理由について混乱しています

このコミュニティと私が得ているすべての助けに感謝します.jQueryの専門家にとって、これは非常に簡単です.私が学ぶのを助けてくれてありがとう.

4

3 に答える 3

4

jQueryis()を使用して、次の項目が 2 つのリストのいずれかの最後であるかどうかを確認したい

$("#next-button").on('click', function () {
    //enable next breadcrumb
    $('.clickable').next().addClass('clickable');
    var nextItem = $('.active').removeClass('active last').next();
    //start again
    if (!nextItem.length) {
        nextItem = $('.item:first,.breadcrumb-cell:first');
    }
    //mark as active
    nextItem.addClass('active');
    //check if is last
    if (nextItem.is('.breadcrumb-cell:last,.item:last')) 
        nextItem.addClass('last');
});

また、クラスが要素に動的に追加されるbreadcrumbsため、クリックイベントの親でイベント委任が必要ですclickable

$(".breadcrumbs").on('click','.clickable .breadcrumb',function () {
    //reset active and last
    $('.active').removeClass('active');
    $('.last').removeClass('last');
    var theID = $(this).data("id");
    //get new item
    var selected = $("#" + theID);
    //mark item and breadcrumb as active
    $(this).parent().add(selected).addClass('active');
    //check if selected is last
    if(selected.is('.item:last'))
        //mark item and breadcrumb as last
        $(this).parent().add(selected).addClass('last'); 
});

更新されたフィドル

于 2013-08-09T19:49:05.367 に答える
2

最後のアクティブな要素 ( DEMO )の css を変更するだけではどうでしょうか。

.item.active:last-child {
    color: green;
    border: 1px solid green;
}

と削除し$('.item').last().addClass('last');ます。

もちろん、css とまったく同じように jQuery で最後の項目をターゲットにすることができます。

$('.item.active:last-child')

編集:私があなたを正しく理解していて、最後のアイテムにいる場合にコードを実行したくない場合は、1つ不足していますnext()

if(!nextItem.next().length) {
    console.log("Now on the last item");
}

if (!nextItem.length) {
    nextItem = $('.item').first();
}
于 2013-08-09T19:34:34.737 に答える