gpt4 book ai didi

javascript - 我无法通过悬停或鼠标输入来取消绑定(bind)并再次重新绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 19:39:40 26 4
gpt4 key购买 nike

我已经尝试了其他人建议的很多不同的方法,但我不明白我做错了什么,真的需要一些帮助。我尝试过使用悬停、mouseenter/mouseleave、开/关、绑定(bind)/取消绑定(bind)的各种组合。

基本上,我可以解除绑定(bind),但之后无法再次绑定(bind)它们。

我将一个 jsfiddle 与一个基本示例放在一起。如果单击“悬停关闭”按钮,鼠标输入将按预期禁用。但是,如果您单击“悬停”按钮后,mouseenter 不会再次启用。

http://jsfiddle.net/770b5p8q/3/

这是“悬停”功能:

$('.square').each(function(){
$(this).bind("mouseenter", function(){
$(this).addClass('active');
});
$(this).bind("mouseleave", function(){
$(this).removeClass('active');
});
});

以下是启用/禁用它的内容:

$('.hover_enabled').click(function(){
$('.square').each(function(){
$(this).bind("mouseenter");
$(this).bind("mouseleave");
});
});

$('.hover_disabled').click(function(){
$('.square').each(function(){
$(this).unbind("mouseenter");
$(this).unbind("mouseleave");
});
});

最佳答案

您应该传递用于绑定(bind)和取消绑定(bind)处理程序的函数,例如:

var mouseEnterHandler = function () {
$(this).addClass('active');
}
var mouseLeaveHandler = function () {
$(this).removeClass('active');
};

$('.square').bind("mouseenter", mouseEnterHandler)
.bind("mouseleave", mouseLeaveHandler);

$('.hover_enabled').click(function () {
$(this).addClass('active');
$('.hover_disabled').removeClass('active');

// I need to bind hover here
$('.square').bind("mouseenter", mouseEnterHandler)
.bind("mouseleave", mouseLeaveHandler);
});

但是代码变得丑陋且难以维护。您可以改用事件委托(delegate):

$(document).on('mouseenter mouseleave', '.square.hoverable', function(event) {
// toggle the class by checking the type of the event
$(this).toggleClass('active', event.type === 'mouseenter');
});

// caching the state changers
var $e = $('.hover_enabled, .hover_disabled').click(function () {
var $this = $(this).addClass('active'),
isHoverable = $this.hasClass('hover_enabled');

// exclude the clicked element from the set and remove the class
$e.not($this).removeClass('active');
$('.square').toggleClass('hoverable', isHoverable);
});

上面的 mouseenter mouseleave 处理程序仅在 .square 元素具有 hoverable className 时执行。您还可以删除事件处理程序并使用 CSS 进行样式设置。

.square.hoverable:hover {

}

http://jsfiddle.net/bztec1f4/

关于javascript - 我无法通过悬停或鼠标输入来取消绑定(bind)并再次重新绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25329550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com