2016-12-20 45 views
0

正如我的标题所示,我使用jQuery中的off-method与mouseover/mouseout结合使用时遇到了问题。使用off() - mouseover()和mouseout()的方法

我的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 - 如果你觉得这个答案正确的,有帮助,然后接受和给予好评这个答案,因为它激励我给予解答这样的其他问题,并帮助他人赶快找到正确答案! –

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>