当点击链接越来越多或越来越少时,列表项使用 Jquery 显示/隐藏
我有一个想要隐藏的大项目列表,然后一个名为 #more 的按钮将再播种 5 个项目。到目前为止,我能够显示更多内容,但是当我使用名为 #less 的按钮显示更少内容时,脚本卡住了。
以下是我的代码和 fiddle
HTML
<a href="#" id="more">more</a>
<a href="#" id="less">less</a>
<ul>
<li>1</li>
<li>2</li>
...
<li>3</li>
</ul>
jQuery
jQuery(function($) {
var visible = 7;
$('ul li:gt('+(visible - 1)+')').hide();
$('#more').click(function() {
if ($('ul li:visible:last').is(':last-child')) {
return false;
}
var currentIndex = $('ul').children('li:visible:last').index(),
nextIndex = currentIndex + (visible + 1);
$('ul li').hide();
$('ul li:lt(' + nextIndex + '):gt(' + currentIndex + ')').show();
});
$('#less').click(function() {
if ($('ul li:visible:first').is(':first-child')) {
return false;
}
var currentIndex = $('ul').children('li:visible:first').index();
var prevIndex = (currentIndex - (visible + 1));
$('ul li').hide();
if(prevIndex == 0)
$('ul li:lt(' + currentIndex + ')').show();
else
$('ul li:lt(' + currentIndex + '):gt(' + prevIndex + ')').show();
});
});
I have a big item list that I wanted to hide, and then a button called #more will sow 5 more. So far I was able to show more, but when I show less with a button called #less, script stuck.
following is my code and fiddle too
HTML
<a href="#" id="more">more</a>
<a href="#" id="less">less</a>
<ul>
<li>1</li>
<li>2</li>
...
<li>3</li>
</ul>
jQuery
jQuery(function($) {
var visible = 7;
$('ul li:gt('+(visible - 1)+')').hide();
$('#more').click(function() {
if ($('ul li:visible:last').is(':last-child')) {
return false;
}
var currentIndex = $('ul').children('li:visible:last').index(),
nextIndex = currentIndex + (visible + 1);
$('ul li').hide();
$('ul li:lt(' + nextIndex + '):gt(' + currentIndex + ')').show();
});
$('#less').click(function() {
if ($('ul li:visible:first').is(':first-child')) {
return false;
}
var currentIndex = $('ul').children('li:visible:first').index();
var prevIndex = (currentIndex - (visible + 1));
$('ul li').hide();
if(prevIndex == 0)
$('ul li:lt(' + currentIndex + ')').show();
else
$('ul li:lt(' + currentIndex + '):gt(' + prevIndex + ')').show();
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这符合我认为你想要的,而且它更干净,你做了比需要的更多的 jQuery 调用。
http://jsfiddle.net/cUUfS/12/
This does what I think you want and it is a lot cleaner, you were doing a lot more jQuery calls than were needed.
http://jsfiddle.net/cUUfS/12/
所以问题出在 less 函数中的 currentIndex 。如果您看到我所说的,它只是查找可见元素的索引,而不是在所有元素中可见的第一个 li 的索引。 @Richard D 的答案对我来说看起来不错,但如果你想知道你的问题出在哪里,我相信它从那里开始
so the problem is with your currentIndex in your less function. It is finding the index of the VISIBLE elements only, not the index of your FIRST li that is visible out of ALL your elements, if you see what im saying. @Richard D's answer looks good to me, but if you wanted to know where your problem was I believe it starts there