基本:
我有一个网页,该网页可将多个内容div加载到页面上,然后在用户单击“加载更多”链接时按顺序显示它们。

此处的示例:JSFiddle Example

$("#load-more").click(function(e) {

    var t = $(this);
    if (t.data('disabled')){
        return;
    }

    var hiddenGroups = $('.group:not(:visible)');
    if (hiddenGroups.length > 0){
        hiddenGroups.first().show();
    } else{
        t.data('disabled', true);
    }
});


基于此示例,我有两个问题:

1)在显示最后一个div时,“加载更多”链接应隐藏其自身,但在我的示例中无法正常运行。

但是,我真的很希望它:

2)隐藏“加载更多” div,而是将功能显示/更改为“隐藏项目”,并在单击时以相反的顺序隐藏内容div。

最佳答案

这就是我要做的:

JSFIDDLE

这个想法:

设置一个变量来指示是否要切换

var load = 'more';


检查我们是否正在加载更多或更少

以及用于切换方向和按钮文字的功能,以停止复制/粘贴相同的javascript。

尽管函数中只有两件事发生,但我正在假设这种情况可能会随着您的应用程序的增长而增长-如果不增长,那么就应该放弃该函数,而只需将其余代码添加进去

完整代码段:

var load = 'more';

$("#load-more").on('click',function (e) {
    // show the next hidden div.group, then disable load more once all divs have been displayed


    // if we are loading more
    if (load == 'more') {

        // get the amount of hidden groups
        var groups = $('.group:not(:visible)');

        // if there are some available
        if (groups.length > 0) {
            // show the first
            groups.first().show();

            // if that was the last group then set to load less
            if (groups.length == 1) {
                switchLoadTo('less');
            }
        }
    // we are loading less
    } else {
        // get the groups which are currently visible
        var groups = $('.group:visible');

        // if there is more than 1 (as we dont want to hide the initial group)
        if (groups.length > 1) {

            // hide the last avaiable
            groups.last().hide();
            // if that was the only group available, set to load more
            if (groups.length == 2) {
                switchLoadTo('more');
            }
        }
    }
});

function switchLoadTo(dir) {
    load = dir;
    $("#load-more").html('Load ' + dir);
}

10-05 20:53
查看更多