在slideUp结束时调用的jQuery removeClass将从所有元素中删除,而不仅仅是这个

时间:2014-01-31 16:26:00

标签: jquery removeclass slideup

我真的在努力学习一些(非常简单的)jQuery。我在页面上有几个框可以向上滚动描述。随着幻灯片的开始,一个类被添加,然后当它结束时,类被删除 - 这是通过类而不是悬停来完成的,这样样式就会一直存在,直到幻灯片完成。

它可以在任何单独的盒子上正常工作但是当我将一个盒子直接移到另一个盒子上时,该类会从第二个盒子中移除,并在第一个项目完成向上滑动时保留在第一个盒子上。

这是我的jquery:

jQuery(document).ready(function () {

    // Rollover on features
    jQuery(".TitleImageBlurbandLinkWrapper a").hover(
        function () {
            thisfeature = jQuery(this);

            // change class when slide starts
            thisfeature.addClass("hover");
            // Show info sliding up
            thisfeature.find(".blurb").stop(true, true).slideDown();
        }, function () {
            // hide info
            thisfeature.find(".blurb").stop(true, true).slideUp({ queue: false, complete: function() {
                    // change class when slide finishes
                    thisfeature.removeClass("hover");
                }}
            );
        }
    );

});

我在开始时将此特性定义为jQuery(this)。当我滚动第二个框时,类“悬停”被正确地添加到第二个框中,但是当第一个框完成时.slideUp该类从第二个框中移除而不是第一个框。

我预计此特征的上下文将保留在声明的动画中,但似乎第二个框重新定义了原始的此特征,因此当第一个动画结束时,类将从第二个框中移除而不是第一个框。< / p>

我该怎么办?

谢谢!

约翰

1 个答案:

答案 0 :(得分:1)

您需要使用闭包变量

jQuery(document).ready(function () {

    // Rollover on features
    jQuery(".TitleImageBlurbandLinkWrapper a").hover(function () {
        var thisfeature = jQuery(this);
        // change class when slide starts
        thisfeature.addClass("hover");
        // Show info sliding up
        thisfeature.find(".blurb").stop(true, true).slideDown();
    }, function () {
        var thisfeature = jQuery(this);

        // hide info
        thisfeature.find(".blurb").stop(true, true).slideUp({
            queue: false,
            complete: function () {
                // change class when slide finishes
                thisfeature.removeClass("hover");
            }
        });
    });
});

当您输入元素1 thisfeature引用该元素时,您将移出以便为正确的元素触发mouseleave动画,但在动画结束之前,您现在输入元素2全局变量{{1此时元素1的mouseleave动画结束并且调用完整的回调但是现在thisfeature是元素2而不是元素1

,这是指元素2而不是元素1