jQuery绑定悬停到"文档"

use*_*645 2 jquery

是否可以将hover()绑定到具有指定选择器的文档,以便为具有匹配属性的动态添加内容分配JS函数?

我一直在看这个主题:JQuery .on()方法,一个选择器有多个事件处理程序,是否可以使用jQuery .on和hover?

而我目前正在使用:

$('.profile-gallery-image-container').on({
    mouseenter: function(){
        $('.delete-image', this).show();
        $('.image-options', this).show();
    },
    mouseleave: function(){
        $('.delete-image', this).hide();
        $('.image-options', this).hide();
    }
}, '.profile-gallery-image-container');
Run Code Online (Sandbox Code Playgroud)

但无法通过匹配选择器将功能传递给新内容.

Vis*_*ioN 8

在委派事件方法中,您应该将事件绑定到一个父元素.profile-gallery-image-container.一种可能的解决方案是将其绑定到<body>(或document)元素:

$('body').on({
    mouseenter: function(){
        $('.delete-image', this).show();
        $('.image-options', this).show();
    },
    mouseleave: function(){
        $('.delete-image', this).hide();
        $('.image-options', this).hide();
    }
}, '.profile-gallery-image-container');
Run Code Online (Sandbox Code Playgroud)