jquery - 按索引遍历定义列表时出现问题

标签 jquery

我有一个包含一年中 12 个月的定义列表。例如,我一次展示 3 个月(一月、二月、三月)。我的目标是在单击最后一个子项时将列表前进到下个月。例如,当单击“三月”时,“四月”将出现,“一月”将消失,显示(二月、三月和四月),依此类推。

这是我的 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

我遇到的问题是它只能工作一次。单击 April 后,没有任何反应。我在调试控制台上也没有收到任何错误。

感谢任何帮助。谢谢。

最佳答案

这可以简化很多,只需使用 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

关于jquery - 按索引遍历定义列表时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4454015/

相关文章:

javascript - eval() 表达式中包含 "return"

jquery - 隐藏 JSTree 中的特定节点

jquery - CSS:在悬停时为元素设置动画

出现在彼此下方的 jQuery 幻灯片元素(应该并排)

javascript - 按值检查复选框

javascript - Jquery "select all"复选框

javascript - 是什么导致此网页在加载时向下滚动?

javascript - 如何自动关闭 BootStrap 警报?

javascript - 一些延迟加载背景图像(b-lazy)没有显示在光滑的轮播中

javascript - 过渡和自动滚动 div