索引似乎在eq期间发生了变化

时间:2012-09-17 11:24:43

标签: jquery

我正在尝试添加一个类,并在单击链接时删除链接的单击事件,然后在单击另一个链接时撤消该操作,我在此处有一个示例http://jsfiddle.net/bdjohnson/zXyb9/4/

但是经过几次点击它就会死掉,我将索引输出到控制台并且它一直在变化,这是错误的做法吗?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我不确定为什么你需要active类以及为什么需要删除click事件,但这是我的解决方案。

$(document).ready(function() {
    $("a.pic_link").on("click", function() {
        var i = $(this).index(); //get the index of the clicked link (I assume that the clicked link length is always the same as the #pic div length)
        var d = $("#pic div"); //get the divs for the #pic element
        d.removeClass("active"); //remove the active class on all of the child divs
        if (d.filter(":visible").length > 0 && d.filter(":visible").index() != i) { //if there is a #pic div visible and it is different from the link that is clicked, then hide it and then show the proper one and add the class
            d.filter(":visible").slideUp(300, function() {
                d.eq(i).addClass("active").slideDown(300, function() {});
            });
        }
        else {
            d.eq(i).addClass("active").slideDown(300, function() {});//just add the class and show the proper element
        }
    });
});​

jsFiddle

另外,我建议您使用CSS初始隐藏#pic div,否则可能会出现#pic div的闪烁。它在jsFiddle中。

答案 1 :(得分:0)

首先,您不需要任何each循环来附加点击处理程序。 只需在jQuery对象上使用click,就会将事件处理程序附加到集合的任何元素。

然后你可以更简单地编写代码:

$(function() {
    var previews = $("#pic div"); // Caching selector
    previews.hide();

    $("a.pic_link").click(function(event) {
        var $this = $(this);
        if (!$this.hasClass("active")) {
            previews.slideUp(300).delay(300).eq($this.index()).slideDown(300);
            $this.addClass("active");
            $this.siblings().removeClass("active");
        }
    });
});​

请注意,您应该使用complete回调,而不是使用delay,如下所示:

previews.slideUp(300, function() {
   previews.eq($this.index()).slideDown(300);
});