Для нескольких списков, eack со своими собственными «показать / скрыть», объединить эти 2 диапазона и поставить элемент управления после каждого списка следующим образом:
<ul class="truncateList" data-list-items="2">
<li>One</li>
...
</ul>
<button class="ShowHideFullLists" type="button">View All</button>
<h2>Second list:</h2>
<ul class="truncateList" data-list-items="4">
<li>A 1</li>
...
</ul>
<button class="ShowHideFullLists" type="button">View All</button>
Тогда будет работать следующий код. См. Это в действии на jsFiddle.
$('.ShowHideFullLists').click (ShowHideFullLists);
$('.ShowHideFullLists').click (); //-- Init list displays.
function ShowHideFullLists () {
var showHideBtn = $(this);
var bShowEm = showHideBtn.data ('bShowEm') || false;
/*--- Find the list for this button. It is a previous sibling,
in the HTML.
*/
var thisBtnsList = showHideBtn.prev ("ul.truncateList");
//--- Show either all or the # from the data-list-items attribute.
ShowItems (thisBtnsList, bShowEm, thisBtnsList.data('listItems'));
//--- Update the show-all flag.
bShowEm ^= true;
showHideBtn.data ('bShowEm', bShowEm);
//--- Update the button text.
if (bShowEm)
showHideBtn.text ('View All');
else
showHideBtn.text ('View Less');
}
function ShowItems (parentNode, bShowAll, numVisible) {
if (bShowAll)
parentNode.find ("> li").show ();
else {
parentNode.find ("> li:lt(" + numVisible + ")").show ();
parentNode.find ("> li:gt(" + (numVisible-1) + ")").hide ();
}
}
Для одной кнопки, чтобы управлять всеми списками...
Тогда ShowHideFullLists
изменяется следующим образом. Смотрите это в действии на jsFiddle. :
ShowHideFullLists (); //-- Init list displays.
//--- Activate the show/hide button.
$('#ShowHideFullLists').click (ShowHideFullLists);
function ShowHideFullLists () {
var showHideBtn = $('#ShowHideFullLists');
var bShowEm = showHideBtn.data ('bShowEm') || false;
//--- Loop through all the different lists.
$("ul.truncateList").each ( function () {
/*--- Show all or the number defined in the
data-list-items attribute.
*/
if (bShowEm)
ShowItems ( $(this), true);
else {
var jThis = $(this);
ShowItems (jThis, false, jThis.data ('listItems') );
}
} );
//--- Update the show-all flag.
bShowEm ^= true;
showHideBtn.data ('bShowEm', bShowEm);
//--- Update the button text.
if (bShowEm)
showHideBtn.text ('View All');
else
showHideBtn.text ('View Less');
}
Также обратите внимание на чувствительность к регистру и рефакторинг черточки в HTML 5 data-
атрибуты .