如何禁用未绑定的事件

时间:2019-06-21 08:28:15

标签: jquery

我正在使用unbind禁用悬停事件,然后想要再次启用它。 怎么做?

$(document).ready(function () {
   if(localStorage.getItem('options')=='disable'){
     $(".pasteOptions").unbind('hover',handler);
  }
 })
var handler = function() {
    alert('hi');
};
$(document).on('click','.copyOptions',function () {
   $('.pasteOptions').bind('hover',handler);
})

它不起作用!

1 个答案:

答案 0 :(得分:0)

问题在于,没有DOM事件hover-仅mouseentermouseleave

您还可以使用jquery .hover,但不能与.on / .off一起使用。

更改为mouseenter mouseleave可让您:

// start with hover on so the .off does something
$('.pasteOptions').hover(handler);

$(document).ready(function () {
    // turn off the hover
    $(".pasteOptions").off('mouseenter mouseleave');
})
$(document).on('click','.copyOptions',function () {
   // turn on the hover 
   // (NB: turn it off first otherwise you get multiple events each time you click,
   //  this wouldn't normally how you do this, it would toggle on a tickbox or similar
   $(".pasteOptions").off('mouseenter mouseleave');
   $('.pasteOptions').hover(handler);
})

var handler = function() {
    // do something on hover
    $(this).toggleClass("hover");
};
.pasteOptions, .copyOptions { height: 100px; width: 100px; border:1px solid blue; }
.hover { border: 1px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='copyOptions'>click me</div>
<div class='pasteOptions'>hover me</div>