2016-12-20 15 views
0

내 제목에서 mouseover/mouseout과 결합 된 JQuery의 메서드를 사용하여 문제가 발생했습니다.mouseover() 및 mouseout()에서 off() 메서드 사용

내 HTML 코드 (관련 부분) :

<h3>Hover</h3> 
<p id="hover">Move the mouse pointer over this paragraph.</p> 
<button id="off">Press the button</button> 

내 JQuery와 코드 (관련 부분) :

$(document).ready(function(){ 
    $("#hover").mouseover(function(){ 
     $("#hover").css("background-color", "green"); 
    }); 
    $("#hover").mouseout(function(){ 
     $("#hover").css("background-color", "lightblue"); 
    }); 
    $("#off").click(function(){ 
     $("#hover").off("click"); 
    }); 
}); 

은 "호버 부분은"잘 작동합니다. 그러나 mouseover 및 mouseout 메서드를 중지 할 단추를 누르면 멈추지 않습니다.

답변

2

이 같은 이벤트 핸들러를 설정하는 jQuery의 unbind를 사용한다 :이 도움이

$("#hover").unbind("mouseover mouseout"); 

$(document).ready(function(){ 
 
    $("#hover").mouseover(function(){ 
 
     $(this).css("background-color", "green"); 
 
    }); 
 
    $("#hover").mouseout(function(){ 
 
     $(this).css("background-color", "lightblue"); 
 
    }); 
 
    $("#off").click(function(){ 
 
     $("#hover").unbind("mouseover mouseout"); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h3>Hover</h3> 
 
<p id="hover">Move the mouse pointer over this paragraph.</p> 
 
<button id="off">Press the button</button>

희망을!

+1

@Waltswen - 그것은이 같은 다른 질문에 대한 답변을 제공하기 위해 나에게 동기를 부여하고 다른 사람을 도움이 당신이 정확하고 동의 및이 대답을 upvote에 다음 도움이 답을 찾을 경우 신속하게 정답을 찾아라! –

0

요소에는 click 이벤트 청취자가없고 mouseovermouseout이 추가되었습니다. 따라서 off()은 효과가 없습니다. 사용 :

$("#hover").off("mouseover mouseout"); 

$(document).ready(function(){ 
 
    $("#hover").mouseover(function(){ 
 
     $("#hover").css("background-color", "green"); 
 
    }); 
 
    $("#hover").mouseout(function(){ 
 
     $("#hover").css("background-color", "lightblue"); 
 
    }); 
 
    $("#off").click(function(){ 
 
     $("#hover").off("mouseover mouseout"); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h3>Hover</h3> 
 
<p id="hover">Move the mouse pointer over this paragraph.</p> 
 
<button id="off">Press the button</button>