绑定和解绑功能

binding and unbinding function

本文关键字:功能 和解 绑定      更新时间:2023-09-26

1) 当#pin_point悬停时,我将两个绝对位置的图像设置为淡入淡出切换,以便它随着淡入淡出效果而变化:

$("#pin_point").hover(function  hoverhandler() {
    $("#pin_point img").fadeToggle('medium');
});

2)单击#pin_point时,我将pin_point img设置为交换为"ex.png":

$("#pin_point").click(function() {
    $("#pin_point img").attr('src','images/ex.png');
});

3)单击#pin_point时,我还取消了#1(上面)中的悬停功能。

:如果我想在再次点击#pin_point时绑定函数,我该怎么办?下面是我拥有的代码,我很难弄清楚。谁能帮忙?

$("#pin_point").click(function() {
    $('#pin_point').unbind('hover', hoverhandler);
    $("#pin_point img").attr('src','images/ex.png');
    $('#pin_point').bind('hover', hoverhandler);
});

hover是一个短手事件。而是解绑mousentermouseleave.此外,将状态信息附加到元素,以便在每次单击时获得备用效果。

function hoverhandler() {
    $("img", this).stop(true, true).fadeToggle('medium');
}
$("#pin_point").hover(hoverhandler);
$("#pin_point").click(function () {
    var $this = $(this),
        enableHover = $this.data('enableHover'), //get the current state
        method = "bind"; //default mathod to bind
    if (!enableHover) {  //if alternate click to disable
         method = "unbind"; //change the method
    } 
    $this[method]('mouseenter mouseleave', hoverhandler); //apply the method
    $this.find("img").prop('src', 'http://placehold.it/40x40');
    $this.data('enableHover', !enableHover);//save the state in the element to toggle between each click
});
如果您

使用的是 jquery 版本>= 1.7,则可以使用 onoff

演示

你要传递给.hover的是一个命名函数表达式。它的名称不应该对其他代码可用,你必须让它成为一个函数声明:

function hoverhandler() {
    $("#pin_point img").fadeToggle('medium');
}
$("#pin_point").hover(hoverhandler);

根据jQuery文档:

调用$( selector ).hover( handlerIn, handlerOut )是以下各项的简写:

$( selector ).mouseenter( handlerIn).mouseleave( handlerOut );

因此,您可以取消绑定

$("#pin_point").off('mouseenter'. hoverhandler).off('mouseleave', hoverhandler );