javascript - 绑定(bind)和解绑函数

标签 javascript jquery html css

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

$("#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 被点击时,我也取消绑定(bind)了 #1(上面)中的悬停功能。

问题:如果我想在再次点击#pin_point 时绑定(bind)函数, 我应该怎么办?下面是我的代码,我很难搞清楚。 谁能帮忙?

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

最佳答案

hover 是一个速记事件。而是取消绑定(bind) 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

Demo

关于javascript - 绑定(bind)和解绑函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414330/

相关文章:

javascript - jQuery:函数未执行

jquery - 使用 jQuery 将值相加然后触发结果

javascript - 提交一个通过ajax调用的表单

javascript - 无法将标题标签居中放置在图像上

javascript - 使用 jquery 计算表中切换行的数量

php - 在现有电子邮件正文的底部添加一个 HTML 元素

javascript - 无缓存和更新在带有 JSP 和 Javascript 的 IE 10 中不起作用

javascript - 如何映射具有未知嵌套级别的数组?

javascript - 如何为浏览器客户端设置 RabbitMQ 绑定(bind)?

javascript - 使用正则表达式从字符串中提取两位数