2016-12-20 2 views
0

Comme mon titre l'indique, j'ai eu des problèmes avec la méthode off de JQuery combinée au mouseover/mouseout.Utiliser la méthode off() sur mouseover() et mouseout()

Mon code HTML (la partie pertinente):

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

Mon JQuery code (la partie pertinente):

$(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"); 
    }); 
}); 

Le "vol stationnaire-partie" fonctionne très bien. Mais quand j'appuie sur le bouton, ce qui est censé arrêter le mouseover et le mouseout-méthodes d'arrêter, ce n'est pas le cas.

Répondre

2

Vous devez utiliser jQuery de unbind, pour déclencher les gestionnaires d'événements comme celui-ci:

$("#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>

Hope this helps!

+1

@Waltswen - Si vous trouvez cette réponse correcte et utile alors accepter et upvote cette réponse comme ça me motive à donner des réponses à d'autres questions comme celle-ci et aide les autres à trouver rapidement la bonne réponse! –

0

L'élément n'a pas d'écouteur d'événement click ajouté, mais mouseover et mouseout. Ainsi, aucun off() n'a aucun effet. Utilisation:

$("#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>