mouseleave在jquery中不起作用

时间:2012-11-12 05:17:09

标签: jquery-ui jquery jquery-plugins jquery-selectors

我的mouseleave无法在我的jquery代码中运行

http://jsfiddle.net/alano/9Dr7T/29/

在下面提供我的js代码

mouseleave: function () {
    $(this).find("div:last").remove();
}

2 个答案:

答案 0 :(得分:2)

问题不在于mouseleave侦听器,问题在于 如何绑定这些事件处理程序以及取消绑定它们。 div正被删除,但每次mouseenter事件都会对其进行读取。由于某些原因,当使用选择器过滤器.on()时,mouseenter事件未被解除绑定。它可能与bubbling occurs when using the selector filter的方式有关。

  

提供选择器时,事件处理程序称为委托。当事件直接发生在绑定元素上时,不会调用处理程序,但仅适用于与选择器匹配的后代(内部元素)。 jQuery将事件从事件目标起泡到附加处理程序的元素(即最里面到最外层的元素),并为该路径上与选择器匹配的任何元素运行处理程序。

现在,我还不是百分之百确定原因,但无论哪种方式,如果您使用直接绑定处理程序,它将起作用:

$('.specialHover').on({
    mouseenter: function() {
        $("<div class='cta'>add image</div>").click(function() {
            var $me = $(this);
            $me.parent().unbind('mouseenter').children('img').attr(
                'src', 
                'http://www.onlinegrocerystore.co.uk/images/goodfood.jpg'
            );
            $me.remove();
        }).appendTo(this);
    },
    mouseleave: function() {
        $(this).find('div:last').remove();
    }
});

请参阅:http://jsfiddle.net/9Dr7T/35/

答案 1 :(得分:0)

你是否尝试过这种方式:

mouseleave: function () {
   $("div:last",this).remove();
}