【问题标题】:When more and less links click, list items show/hide using Jquery当越来越少的链接点击时,列表项使用 Jquery 显示/隐藏
【发布时间】:2011-10-20 13:08:59
【问题描述】:

我有一个想要隐藏的大项目列表,然后一个名为#more 的按钮将再播种 5 个。到目前为止,我能够显示更多内容,但是当我使用名为 #less 的按钮显示更少内容时,脚本卡住了。

以下是我的代码和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();
});
});

【问题讨论】:

  • Fiddle 使用 mootools,改为 jquery
  • 另外,您是要显示/隐藏更多/更少的项目还是在列表中前后移动?

标签: jquery html css show-hide html-lists


【解决方案1】:

这是我认为你想要的,它更干净,你做了比需要的更多的 jQuery 调用。

jQuery(function($) {
    var visible = 7, $lis = $('ul li'), max = $lis.length;        
    function showUpToIndex(index) {
        $lis.hide();
        $lis.slice(0, index).show();
    }

    showUpToIndex(visible);

    $('#more').click(function(e) {
        e.preventDefault();
        visible = visible + 5;
        if (visible > max) visible = max;

        showUpToIndex(visible);
    });

    $('#less').click(function(e) {
        e.preventDefault();
        visible = visible - 5;
        if (visible < 0) visible = 0;

        showUpToIndex(visible);
    });
});

http://jsfiddle.net/cUUfS/12/

【讨论】:

    【解决方案2】:

    所以问题在于您的 less 函数中的 currentIndex 。如果您看到我在说什么,它只会找到 VISIBLE 元素的索引,而不是在所有元素中可见的 FIRST li 的索引。 @Richard D 的回答对我来说看起来不错,但是如果您想知道问题出在哪里,我相信它从那里开始

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      相关资源
      最近更新 更多