将相对于选择器的变量传递给多个 jQuery 事件

Pass variable relative to the selector to multiple jQuery events

本文关键字:jQuery 事件 相对于 选择器 变量      更新时间:2023-09-26

我正在寻找一种方法来将相对于元素的变量传递给mouseenter和mouseleave事件。例如,如果我有:

jQuery('.element').on({
    mouseenter: function () {
        var $child = jQuery(this).find('.child');
        $child.fadeIn();
    },
    mouseleave: function () {
        var $child = jQuery(this).find('.child');
        $child.fadeOut();
    }    
});

有没有办法避免两次定义$child变量?我能够使用 .hover() 解决这个问题,但是我现在无法使用它,因为我在动态生成的元素上调用它,.hover() 将不起作用。

您可以使用这种方式委派两个事件:

jQuery(document).on("mouseenter mouseleave", ".element", function(e){
    jQuery(this).find('.child').fadeToggle();
    // you can check for e.type for more complex logic    
});

使用不同处理程序委派的语法为:

jQuery(document).on({
    mouseenter: function () {
        //...
    },
    mouseleave: function () {
        //...
    }    
}, ".element");

使用类似的东西:

jQuery('.element').on({
    mouseenter: function (e) {
        var ele = e.currentTarget;
        ele.fadeIn();
    },
    mouseleave: function (e) {
        var ele= e.currentTarget;
        ele.fadeOut();
    }    
});

您可以在两个事件中重用相同的函数,如下所示:

jQuery('.element').on({
    mouseenter: function () {
        handleFade("enter", jQuery(this));
    },
    mouseleave: function () {
        handleFade("leave", jQuery(this));
    }    
});
function handleFade(state, $elem){
    var $child = $elem.find('.child');
    if(state=="enter"){
        $child.fadeIn();
    } else if(state=="leave"){
        $child.fadeOut();
    }
}