2012-04-24 4 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> 

에 따라 애니메이션, 그것에 대한 hover 조치는 여전히 한 번 그 클래스를했다 요소에 적용되고있다. 이 문제를 어떻게 방지 할 수 있습니까?방지 요소가 이전 클래스

http://jsfiddle.net/gSfc3/

는 여기가 jsFiddle입니다. 위에서 볼 수 있듯이 click 함수를 실행하여 클래스를 제거한 후에는 마우스 오버시 배경이 계속 변경됩니다. 코드에서

답변

1

이벤트 핸들러가 노드에 바인딩, 그래서 노드가 더 이상 특정 클래스 이름을 소유하지 않는 경우는 문제가되지 않습니다. 수동으로 이벤트를 .unbind() 개 필요하거나 jQuerys .off() 메소드를 사용하십시오. 당신이 해당 노드에 바인딩 된 다른 이벤트 핸들러가 아니라는 것을 확신 할 수있는 경우

그래서, 바로이 해당 노드에서 어떤 이벤트 핸들러를 제거합니다

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

호출합니다. 당신이 구체적으로해야하는 경우에만 네임 스페이스 .myNamespace

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

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

, $('.example').hover는 mouseenter를 부착하고 각 요소에 직접하는 MouseLeave.

- 또는

더 나은 솔루션이 핸들러 CSS 선택을 기반으로하기 때문에, on

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

가 예상대로 작동합니다 example 클래스를 제거, 그 코드를 사용하여 위임을 사용할 수 있습니다, .hover은 요소에 직접 부착됩니다.

+0

또는 .unbind ('mouseenter mouseleave') –

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

데모 : http://jsfiddle.net/gSfc3/1/

+0

live는 사용되지 않습니다. –

0

이 시도 내에서 어떤 이벤트를 바인딩 해제에, 당신은 너무

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

처럼을의 네임 jQuerys 이벤트를 사용하고이 호출을 사용할 수 있습니다 :

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