Javascript 显示及;单击后按顺序隐藏div

Javascript 显示及;单击后按顺序隐藏div,javascript,jquery,html,css,Javascript,Jquery,Html,Css,基础知识: 我有一个网页,它将几个内容div加载到一个页面,然后在用户单击“加载更多”链接时按顺序显示它们 示例如下: 基于此示例,我有两个问题: 1)当显示最后一个div时,“加载更多”链接应隐藏其自身,但在我的示例中功能不正常 但是,我真的希望: 2)隐藏“加载更多”div,并在单击时将功能显示/更改为“隐藏项目”,并按相反顺序隐藏内容div。 请参阅下面的代码片段。可能不是最优化的代码,但您已经了解了这个想法,并且可以在实现时对其进行优化 var load = true; $("#loa

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

示例如下:

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

1)当显示最后一个div时,“加载更多”链接应隐藏其自身,但在我的示例中功能不正常

但是,我真的希望:

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

请参阅下面的代码片段。可能不是最优化的代码,但您已经了解了这个想法,并且可以在实现时对其进行优化

var load = true;

$("#load-more").click(function(e) {
    // show the next hidden div.group, then disable load more once all divs have been displayed
    var t = $(this);
    if (t.data('disabled')){
        return;
    }

    var hiddenGroups = $('.group:not(:visible)');

    if(load) {
        hiddenGroups.first().show();
    } else {
        $('.group:visible').last().hide();
    }

    if (hiddenGroups.length > 1){
        jQuery("#load-more").html("Load");
        load = true;
    } else {
        jQuery("#load-more").html("Hide");
        load = false;
    }
});

我会这样做:

这个想法:

设置一个变量,指示是否要进行更多或更少的切换

var load = 'more';
检查我们是否装载了更多或更少的货物

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);
}