Hide all li elements and show the first 2 and toggle them by button
Assume I have
<ul>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
I want jQuery code to hide all <li>
then show the fist and the second one
then append()
an additional <li>more</li>
that is used 开发者_Python百科to toggle the
hidden li.
this should do it ..
// hide all li and then show the first two
$('ul li').hide().filter(':lt(2)').show();
// append a li with text more that on click will show the rest
$('ul').append('<li>more</li>').find('li:last').click(function(){
$(this).siblings(':gt(1)').toggle();
});
demo :
$('ul li').hide().filter(':lt(2)').show();
$('ul').append('<li>more</li>').find('li:last').click(function() {
$(this).siblings(':gt(1)').toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
Update to add changing text from more to less ..
$('ul li')
.hide()
.filter(':lt(2)')
.show();
$('ul')
.append('<li><span>more</span><span class="less">less</span></li>')
.find('li:last')
.click(function(){
$(this)
.siblings(':gt(1)')
.toggle()
.end()
.find('span')
.toggle();
});
needs a css rule of .less{display:none}
demo :
$('ul li')
.hide()
.filter(':lt(2)')
.show();
$('ul')
.append('<li><span>more</span><span class="less">less</span></li>')
.find('li:last')
.click(function() {
$(this)
.siblings(':gt(1)')
.toggle()
.end()
.find('span')
.toggle();
});
.less {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
Is this something like you're looking for?
$('li').hide()
.slice(0,1)
.addClass('fixed')
.show();
$('<li class="toggle">more</li>')
.appendTo('ul')
.click( function() {
$('li:not(.toggle,.fixed)').toggle();
});
精彩评论