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