2012-04-24 18 views
3
$('.example').hover(
    function() { 
    $(this).css('background','red'); 
    }, 
    function() { 
    $(this).css('background','yellow'); 
    } 
); 

$('.test').click(function(){ 
    $(this).css('marginTop','+=20px').removeClass('example'); 
    } 
); 

<div class="text example"></div> 

儘管該類example是看似切除,hover行動爲它仍然被應用到曾經那個類的元素。我怎樣才能防止這一點?防止元素動畫基於以前的類

http://jsfiddle.net/gSfc3/

這是的jsfiddle。如您所見,執行click函數刪除類後,背景仍會在懸停時更改。

回答

1

事件處理程序綁定到節點,所以如果節點不特定的className了也沒關係。您需要手動輸入.unbind()這些事件,或更好地使用jQuerys .off()方法。

所以,如果你可以肯定,有沒有綁定到該節點的任何其他事件處理程序,只需調用

$(this).css('marginTop','+=20px').removeClass('example').off(); 

這會從該節點刪除任何事件處理程序。如果您需要具體,你可以使用jQuerys 事件命名空間,像這樣

$('.example').on('mouseenter.myNamespace' 
    function() { 
     $(this).css('background','red'); 
    } 
).on('mouseleave.myNamespace' 
    function() { 
     $(this).css('background','yellow'); 
    } 
); 

,並使用此電話只解綁是命名空間.myNamespace

$(this).css('marginTop','+=20px').removeClass('example').off('.myNamespace'); 
0

$('.example').unbind('mouseenter').unbind('mouseleave')

在代碼中,$('.example').hover附加一個的mouseenter並直接鼠標離開到每個元素。

- 或 -

更好的解決方案可能是因爲處理程序是基於CSS選擇使用代表團on

$(document.body).on('mouseenter', '.example', function() { ... }); 
$(document.body).on('mouseleave', '.example', function() { ... }); 

使用的代碼,去掉example類如預想的那樣工作,而.hover直接附加到元素。

+0

或者只是.unbind( '的mouseenter鼠標離開') – 2012-04-24 18:32:09

0
$('.example').live({ 
    mouseenter:function() { 
     $(this).css('background','red'); 
    }, 
    mouseleave:function() { 
     $(this).css('background','yellow'); 
    } 
}); 

演示:http://jsfiddle.net/gSfc3/1/

+0

現場已被棄用 – 2012-04-24 18:31:58

0

試試這個範圍內的任何事件:

$('.test').hover(
    function() { 
     $('.example').css('background','red'); 
    }, 
    function() { 
     $('.example').css('background','yellow'); 
    } 
);