1

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

但是点击几下它就死了,我将索引输出到控制台并且它一直在变化,这是错误的方法吗?

任何帮助是极大的赞赏。

4

2 回答 2

1

I'm not sure why you need the active class and why you need to remove the click event, but here is my solution.

$(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

In addition, I would suggest that you use CSS to initially hide the #pic div's, otherwise there may be a flicker of the #pic div's showing up. It is in the jsFiddle.

于 2012-09-17T12:11:58.393 回答
0

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

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

$(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");
        }
    });
});​

请注意,您应该使用completecallback 而不是 using delay,如下所示:

previews.slideUp(300, function() {
   previews.eq($this.index()).slideDown(300);
});
于 2012-09-17T11:45:53.273 回答