通过索引遍历定义列表的问题

时间:2010-12-15 19:31:33

标签: jquery

我有一个包含一年中12个月的定义列表。我有3个月的时间,例如(1月,2月,3月)。我的目标是让列表进入下一个月点击最后一个孩子。例如,当单击March时,将显示April,并且1月将消失显示(2月,3月和4月),依此类推。

这是我的HTML

<div id="archive" class="archive">
    <div>Archive</div>
    <dl>
        <dt>January</dt>
        <dt>February</dt>
        <dt>March</dt>
        <dt>April</dt>
        <dt>May</dt>
        <dt>June</dt>
        <dt>July</dt>
        <dt>August</dt>
        <dt>September</dt>
        <dt>October</dt>
        <dt>November</dt>
        <dt>December</dt>
    </dl>
</div>

这里是jQuery代码

$(document).ready(function() {
$("#archive dl dt:gt(2)").hide();

$("#archive dl dt").each(function(index, value) {
        $(this).click(function() {
            if ($("#archive dl dt:visible").size() == (index + 1)) {
                $(this).next("dt").show(500);
                $("#archive dl dt:eq(" + (index - 2) + ")").hide(500);
            }
        });
    });
});

我也有一个jfiddle链接: Live Example

我遇到的问题是它只能运行一次。点击四月时,没有任何反应。我也没有在调试控制台上出现任何错误。

感谢任何帮助。感谢。

3 个答案:

答案 0 :(得分:2)

这可以简化很多,只需使用next()prev()

$("#archive dl dt:gt(2)").hide();

// we'll use not(":last") so that December can't be clicked
$("#archive dl dt").not(":last").each(function(index, value) {
    $(this).click(function() {
            $(this).next().show(500);
            $(this).prev().prev().hide(500);
    });
});

Try it here

答案 1 :(得分:1)

我只是更改if()语句,以检查.next('dt')元素.is(':hidden')是否。

示例: http://jsfiddle.net/patrick_dw/y5ngh/3/

if ($(this).next("dt").is(':hidden')) {
    $(this).next("dt").show(500);
    $("#archive dl dt:eq(" + (index - 2) + ")").hide(500);
}

这是两个方向的完整版本。它可以简化一点,但这很有效。

示例: http://jsfiddle.net/patrick_dw/y5ngh/5/

$("#archive dl dt").each(function(index, value) {
    $(this).click(function() {
        if ($(this).next("dt").is(':hidden')) {
            $(this).next("dt").show(500);
            $("#archive dl dt:eq(" + (index - 2) + ")").hide(500);
        } else if ($(this).prev("dt").is(':hidden')) {
            $(this).prev("dt").show(500);
            $("#archive dl dt:eq(" + (index + 2) + ")").hide(500);
        }
    });
});

更新版本,减少选择和冗余:http://jsfiddle.net/patrick_dw/y5ngh/11/

$("#archive dl dt").click(function() {
    var $th = $(this), dir = ['next', 'prev'];
    if ($th.prev("dt").is(':hidden')) dir.reverse();
    else if ($th.next("dt").is(':visible')) return;
    $th[dir[0]]("dt").show(500)[dir[1] + 'Until'](':hidden').last().hide(500);
}).slice( 3 ).hide();

答案 2 :(得分:0)

使用此

$(document).ready(function() 
{
    $("#archive dl dt:gt(2)").hide();
    $("#archive dl dt").click
    (
            function()
            {
                $("#archive dl dt").hide();
                if($(this).next()!=null && $(this).next().length!=0 && $(this).next().next()!=null && $(this).next().next().length!=0)
                {
                    $(this).next().show();
                    $(this).next().next().show();
                }
             }
    );
});
相关问题