为什么这个jQuery代码只适用于一次迭代?

时间:2012-01-19 02:27:13

标签: javascript jquery css live

基本上我有一个放置图标,它应该展开并折叠它下面的区域。它会改变背景位置并向下指向并显示一些内容。再次单击它会折叠内容并更改背景位置。下面是我写的,但它不能正常工作。

$(function() {
    $(".aclass").live('click' , function() {
        $(this).css("background-position","-156px -42px").addClass("new");

        $(".blockedDiv").hide();
        $(".mystery").css("max-height","189px");
    });

    $(".new").live('click', function() {
        $(this).css("background-position","0px 0px");
        $(".blockedDiv").show();
        $(".mystery").css("max-height","1007px");
    });
});

我的两个问题: 1:为什么这只适用于一次迭代 2:有没有更好的方法来实现这一目标。

4 个答案:

答案 0 :(得分:3)

您没有删除自己添加的new课程。因此,当你再次点击它时,第二个事件处理程序也会触发,反转第一个事件处理程序所做的事情。

作为一个侧面注释 - 斜杠提示,您想要的是指定显式CSS规则,您可以使用jQuery进行切换,这样您就不必破解(相对)复杂的逻辑。

.mystery { max-height:10007px; }
.mystery.flagged { max-height:189px; }

.aclass { background-position:0 0; }
.aclass.flagged { background-position:-156px -42px; }

然后在你的jQuery中:

$('.aclass').live('click', function () {
    $('.mystery').toggleClass('flagged');
    $(this).toggleClass('flagged');
    $('.blockedDiv').toggle();
});

答案 1 :(得分:1)

Richard已经指出了你的代码的问题。您需要切换new类。

更简洁的方法可能是使用toggleClass() jQuery函数。

您定义了两个CSS类:

.hiddenDiv {...}
.expandedIcon {...}
.collapsedIcon {...}

和JS:

$(function(){
   $(".aClass").click(function(){
         $(".blockDiv").toggleClass("hiddenDiv");
         $(this).toggleClass("expandedIcon");
         $(this).toggleClass("collapsedIcon");

    });
})

在HTML中,有类似的内容:

<div class="aClass collapsedIcon"> </div> <!-- initially collapsed -->
<div class="blockDiv hiddenDiv"> </div> <!-- initially hidden -->

答案 2 :(得分:0)

这是一种稍微不同的做法,应该有效。

$(function() {
    $(".aclass").live('click' , function() {
        var $this = $(this), // cache the result of the function to prevent recreating it each time
            is_expanded = $this.hasClass('new');
        $this.css({'background-position': (is_expanded ? '-156px -42px' : '0px 0px')});
        $('.mystery').css({'max-height': (is_expanded ? '189px' : '1007px')});
        if (is_expanded) {
            $('.blockedDiv').show();
            $this.removeClass('new');
        } else {
            $('.blockedDiv').hide();
        }
        $this.addClass('new'); // won't do anything if it already has the class
    });
});
编辑:正如@Richard Neil Ilagan所说,你(和我)忘了删除new课程。

答案 3 :(得分:0)

它运作得很好。 jsFiddle

点击“.aclass”即可: 1)设置'this'的背景位置 2)添加“new”类(这使它成为BOTH处理程序的目标) 3)隐藏不同的东西.blockedDiv 4)设置.mystery的最大高度

点击“.new”,它会: 1)设置'this'的背景位置 2)显示不同的东西.blockedDiv 3)设置.mystery的最大高度

你打算做什么?也许你想在第一个处理程序中删除类.aclass int,在第二个处理器中执行相反的操作(添加.aclass remove .new)?

相关问题