can't unbind mouse leave when clicking

匆匆过客 提交于 2019-12-12 01:53:22

问题


I have a jquery script, where if you mouseenter and element, something shows, and disappears when you mouseleave. I'm trying to unbind the mouseleave when user clicks, so that "something" stays showing when user leaves. Is this the correct way to do it? If so, can someone help me get this script to work?

Thank you!

$('.block').live("mouseenter",function(){
        var id= $(this).attr('id');
        $('#arrowPreview'+id).show();


    }).live("mouseleave",function(){
        var id= $(this).attr('id');
        $('#arrowPreview'+id).hide();

    }).live("click",function(){
        var id= $(this).attr('id');
        $('#arrowPreview'+id).show();
        $(this).unbind("mouseleave");
    });

Thank you!


回答1:


So I don't think what you want is exactly possible. The problem appears to be the use of .live and unbind. You can unbind the mouseleave event with .die. However, the selector used must match the one originally used to bind the event, in your case .block. I am thinking that this obviously is bad. Example Fiddle of .die

http://jsfiddle.net/EZNDg/

I think that instead you need to bind using an explicit selector for the current element, so perhaps using .each with your selector and then binding with $(this). This should allow die to work. I will mess with this Fiddle and see if it is true.




回答2:


You need to create the functions to execute on events as variables to ensure integrity of your javascript so for your example:

var fShow = function(){
    var id= $(this).attr('id');
    $('#arrowPreview'+id).show();
};

var fHide = function(){
    var id= $(this).attr('id');
    $('#arrowPreview'+id).hide();
};

var fClick = function(){        
    var id= $(this).attr('id');
    $('#arrowPreview'+id).show();
};

$('.block').bind('mouseenter',fShow);
$('.block').bind('mouseleave',fHide);
$('.block').unbind('mouseleave',fHide);



回答3:


events bound with live are unbound with die



来源:https://stackoverflow.com/questions/7734602/cant-unbind-mouse-leave-when-clicking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!