如何在第二次点击时锁定功能

How can I lock a function on the second click

本文关键字:锁定 功能 第二次      更新时间:2023-09-26

我有一个侧边栏,可以在悬停时展开。

因为展开、折叠有时会打扰,当有人点击侧边栏时,我想解开悬停的绑定。

底部的代码用于第一次取消绑定,但第二次单击以再次重新启用悬停不起作用:

    $('.action').click(function(){
        $(this).unbind('mouseenter').unbind('mouseleave');
        $(this).click(function(){
            $(this).bind('mouseenter').bind('mouseleave');
        });
    });

那么锁定时如何再次绑定悬停(如果构造,请不要(。

问候

$('.action').on('mouseenter mouseleave', doStuffOnHover); //initial handler
var bound = true;
$('.action').on('click', function(){
      $(this)[bound ? 'off' : 'on']('mouseenter mouseleave', doStuffOnHover);
      bound=bound ? false:true;
});
function doStuffOnHover() {
   //do stuff here
}

小提琴

如果在鼠标输入/离开时执行不同的操作,您当然需要两个功能。

您需要绑定实际事件.bind('mouseenter', function () { /* whatever */ });。 jQuery不会自动知道你想重新绑定已经存在的东西。 如果需要,可以使用命名函数,这样就不必重写它。