can't unbind mouse leave when clicking

2019-09-15 01:12发布

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!

3条回答
ゆ 、 Hurt°
2楼-- · 2019-09-15 01:32

events bound with live are unbound with die

查看更多
beautiful°
3楼-- · 2019-09-15 01:41

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);
查看更多
甜甜的少女心
4楼-- · 2019-09-15 01:50

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.

查看更多
登录 后发表回答