【问题标题】:Find out if last div is visible and then disable next button?找出最后一个 div 是否可见,然后禁用下一个按钮?
【发布时间】:2012-11-06 02:24:05
【问题描述】:

我有一个跨多个 div 的表单,这些 div 使用 jQuery 打开和关闭显示。我想在第一个和最后一个 div 可见时禁用下一个和上一个按钮。

根据我对 jQuery 的了解,这听起来很容易,但事实证明,考虑到我当前的代码,这比我想象的要困难。

这是我当前的下一个和上一个按钮功能

    var sel = "div[data-type='form']";
    var current = $(sel).get(0);

    $(sel).not(current).hide();

    $("#next").click(function () {
        if ($(form).valid()) {
            current = $(current).next(sel);
            $(current).show();
            $(sel).not(current).hide();
        } 
    });

    $("#prev").click(function () {
        current = $(current).prev(sel);
        $(current).show();
        $(sel).not(current).hide();

    });

这里是目前正在发生的事情http://jsfiddle.net/GZ9H8/6/

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    这个works(注意:出于测试目的,我删除了验证)。

    $("#next").click(function () {
        if (true) {
            current = $(current).next(sel);
            $(current).show();
            $(sel).not(current).hide();
            if (!$(current).next(sel).get(0)){
                $(this).hide();
            }
            if ($(current).prev(sel).get(0)){
                 $("#prev").show();
            }
        }
    });
    
    $("#prev").click(function () {
        current = $(current).prev(sel);
        $(current).show();
        $(sel).not(current).hide();
        if ($(current).next(sel).get(0)){
           $("#next").show();
        }
        if (!$(current).prev(sel).get(0)){
            $(this).hide();
        }
    });
    

    请注意,上一个按钮可能应该从一开始就隐藏起来。此外,您可以根据需要禁用而不是隐藏。

    【讨论】:

    • 太棒了,这很完美——但是这里到底发生了什么?更具体地说,if (true) 部分是什么意思?
    • @user1735913:抱歉,if(true) 部分只是为了避免您的表单验证,因为我无法每次都填写您的表单以查看上一个/下一个按钮是否正常工作。只需重新插入您的 $(form).valid() 即可。
    • 哦,好吧。明白了。非常感谢:)
    【解决方案2】:

    这可能有用:

    $("#next").click(function () {
        if ($(form).valid()) {
            current = $(current).next(sel);
            $(current).show();
            $(sel).not(current).hide();
    
            // Last element's index is equal to length - 1
            $(this).attr('disabled', current.index(sel) == $(sel).length - 1);
            // First element's index is equal to 0
            $("#prev").attr('disabled', current.index(sel) == 0);
        }
    });
    
    $("#prev").click(function () {
        current = $(current).prev(sel);
        $(current).show();
        $(sel).not(current).hide();
    
        // Last element's index is equal to length - 1
        $("#next").attr('disabled', current.index(sel) == $(sel).length - 1);
        // First element's index is equal to 0
        $(this).attr('disabled', current.index(sel) == 0);
    });
    

    问候

    【讨论】:

    • 您禁用它们,但您也需要重新启用它们!
    • 他说了什么^。否则这也是一个有效的答案。感谢您的帮助:)
    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    相关资源
    最近更新 更多