我想知道是否可以在 UL
中显示 X
数量的元素,并且可以隐藏其余元素。
我有一个通知小部件,我想最多显示 5 个警报。当一个被移除时,列表中的下一个元素将被显示,所以我不必重新制作列表。
这是我的 mustache 代码:
var template =
'<div class="notifications js-notifications">' +
'<h3>Notifications</h3>' +
'<ul class="notifications-list">' +
'<li class="item no-data">You don\'t have notifications</li>' +
'{{#items}}' +
// I would like the li element to be hidden after the first 5 items
'<li class="item js-item" data-id="{{id}}" alert-id="{{alertid}}">' +
'<div class="details">' +
'<span class="title">{{title}}</span>' +
'<span class="date">{{formattedDate}}</span>' +
'</div>' +
'<button type="button" class="button-default button-dismiss js-dismiss">×</button>' +
'</li>' +
'{{/items}}' +
'</ul>' +
'<a href="#" class="show-all">Show all notifications</a>' +
'</div>';
container
.append(Mustache.render(template, { items: items }))
.find('.js-count').attr('data-count', items.length).html(items.length).end()
.off('click', '.js-show-notifications')
.on('click', '.js-show-notifications', function(event) {
$(event.currentTarget).closest('.js-show-notifications').toggleClass('active').blur();
return true;
})
.off('click', '.js-dismiss')
.on('click', '.js-dismiss', function(event) {
var item = $(event.currentTarget).parents('.js-item');
var alert_ID = +item.attr("alert-id");
console.log("Item removed: " + alert_ID);
var removeItem = function() {
item[0].removeEventListener(cssTransitionEnd, removeItem, false);
item.remove();
// Display the next item in the UL here
/* update notifications' counter */
var countElement = container.find('.js-count');
var prevCount = +countElement.attr('data-count');
var newCount = prevCount - 1;
countElement
.attr('data-count', newCount)
.html(newCount);
if(newCount === 0) {
countElement.remove();
container.find('.js-notifications').addClass('empty');
}
};
item[0].addEventListener(cssTransitionEnd, removeItem, false);
item.addClass('dismissed');
return true;
});
最佳答案
你可以这样做。我将把它包装在 click 事件
中进行演示:检查下面的代码段
var firstToshow = 0;
var lastToShow = 5;
$("ul li").hide();
$("ul li").slice(firstToshow, lastToShow).show();
$("ul").on('click', function() {
firstToshow++;
lastToShow++;
$("ul li").hide();
$("ul li").slice(firstToshow, lastToShow).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
<li>16</li>
<li>18</li>
<li>19</li>
<li>20</li>
</ul>
关于javascript - 我如何在 UL 中显示 X 项并隐藏其余项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35703003/