4

Related Blog Posts&などのコンテンツをリストするページにいくつかのブロックがありますRelated Articles

これらのブロックは、すべての結果を返すようにコーディングされています。しかし、リストが長くなりすぎないように、デフォルトで 3 つの項目のみを表示するようにリストを設定し、クリックするとアコーディオン効果がトリガーされ、残りの項目があればそれを表示する「さらに表示」ボタンで作業しました。

私が抱えている問題は、ブロックに 3 つ以上の項目がない場合でも、より多くのボタンが表示されることです。size()各ブロックを個別にカウントするのではなく、両方のブロックの合計の子をカウントしているようです。

もちろん、2 つの一意のセレクターをターゲットにして機能させることもできます。ただし、別のアコーディオン ブロックが必要になるたびに常に新しいセレクターを追加することなく、このスクリプトを再利用できるようにしたいと考えています。

ブロックにアコーディオン効果を適用したいときはいつでも、HTMLリストを含むブロックの外側のラッパーに「アコーディオン」のクラスを追加するだけです。

これが私のコードです。

(function($) {
    $(document).ready(function() { 
        /**
         * Define variables
         */
        var parentSelector = $('.block-views .accordion ul'),
    controlsHTML = $('<div class="show-more"><button>Show More</button></div>'),
    count = $(parentSelector).children().size();

        /**
         * Wrap all items we want to show/hide except for the first 3
         */
        $(parentSelector).children().not(':nth-child(1), :nth-child(2), :nth-child(3)').wrapAll('<div class="slide-content" />');

        /**
         * Hide content that should be hidden by default
         */
        $('.slide-content').hide();

    /**
     * Insert open/close button if there are more than three items in list
     */
    if (count > 3) {
    $(controlsHTML).insertAfter(parentSelector);
    }

        /**
         * Build the expanding content container and attach it to a click event
         */
        $(".show-more button").toggle(
            function () {
                $(this).toggleClass('collapse');
                $(this).text("Show Less");
                $(this).parents('.item-list').find('.slide-content').slideDown();
            },
            function () {
                $(this).toggleClass('collapse');
                $(this).text("Show More");
                $(this).parents('.item-list').find('.slide-content').slideUp();
            }
        );
    });
}(jQuery));
4

1 に答える 1

1

アコーディオンを繰り返し処理し、それぞれの長さを確認する必要があります。

(function($) {
    $(function() { 

        $('.block-views .accordion ul').each(function(i,elm) {
            var ctrl = $('<div class="show-more"><button>Show More</button></div>'),
                count = $(this).children().length;
            if (count > 3) {
                $(this).after(ctrl);
            }
        });

        $(".show-more button").data('state', true).on('click', function () {
            var state = $(this).data('state');

            $(this).toggleClass('collapse').text("Show "+(state?'Less':'More'));
                   .parents('.item-list').find('.slide-content').slideToggle().data('state' !state);
        });
    });
}(jQuery));​

また、そのように使用されたトグルも非推奨になっていることに注意してください。

于 2012-11-05T17:35:54.323 に答える