2012-04-25 55 views
2

当我“removeClass('下')”,它删除了css类,但当我再次单击对象时,它执行相同的操作。jQuery的动画和删除类与addClass

我想通过删除CSS代码来消除点击功能的工作能力。我究竟做错了什么?

$('.below').click(function() { 
    $(this).removeClass('below'); 
    $('#welcome').removeClass('fadeInLeft, bounceOutLeft').addClass('fadeOutLeft'); 
    $('#welcome_search').delay('500').animate({"top": "-=140px"},"slow"); 
}); 

我的HTML看起来类似于此:

<div id="welcome_item" class="below"> 
    stuff 
</div> 

请这方面的帮助,谢谢。

如果我想在更换课程后重新绑定点击,该怎么办?

$('.below').click(function() { 
    $(this).unbind('click').removeClass('below').addClass('above'); 
    $('#welcome').removeClass('fadeInLeft bounceOutLeft').addClass('fadeOutLeft'); 
    $('#welcome_search').delay('500').animate({"top": "-=140px"},"slow"); 
}); 

$('.above').click(function() { 
    $(this).removeClass('above').addClass('below'); 
    $('#welcome_search').animate({"top": "+=140px"},"slow"); 
    $('#welcome').removeClass('fadeInLeft bounceOutLeft fadeOutLeft').delay('500').addClass('fadeInLeft'); 
}); 

回答

3

到那个jQuery代码运行时,click事件已绑定到该元素与.below类,每次你点击元素的时候,jQuery的实际上不检查类的该元素了,所以删除类不会帮助你。

您可以使用unbind代替

http://api.jquery.com/unbind/

$('.below').click(function() { 
    $(this).unbind('click'); 
    $('#welcome').removeClass('fadeInLeft, bounceOutLeft').addClass('fadeOutLeft'); 
    $('#welcome_search').delay('500').animate({"top": "-=140px"},"slow"); 
}); 
+0

这似乎工作。但是如果我添加Class('above')呢?并为此做一个单独的点击功能?我如何使它可点击? – Josh 2012-04-25 05:23:59

1

使用.off()

卸下类是不够的,该事件已连接到该节点,所以你应该去除附在太事件。

DEMO

0

你可以选择使用

$('.below').live("click",function(){}); 
0

刚刚解除绑定的情况下,当你删除类。

$('#foo').unbind('click'); 

所以你的js代码应该看起来像这样。

$('.below').click(function() { 
    $(this).unbind('click'); 
    $(this).removeClass('below'); 
    $('#welcome').removeClass('fadeInLeft, bounceOutLeft').addClass('fadeOutLeft'); 
    $('#welcome_search').delay('500').animate({"top": "-=140px"},"slow"); 
});