1

我正在使用 Infinite Scroll 来显示一些内容,但我无法将一些 mouseenter/mouseleave 事件绑定到新生成的项目。

我知道我需要将 .on 绑定到页面上已经存在的容器,但是我无法弄清楚改变当前切换的 jQuery 的语法。

这是当前的js:

$(document).ready(function() {
    $('.grid-box .actions').hide();

    $('.grid-box').on({
        mouseenter: function () {
            $(this).find('.actions').show();
        },
        mouseleave: function () {
            $(this).find('.actions').hide();
        }
    });

});

主容器是#grid-container,每个单独的项目是.grid-box。如何更改上述内容,以便在进入/离开 .grid-box 时显示/隐藏操作?

我想我需要一些类似的东西:

$('#grid-container').on('mouseenter mouseleave', '.grid-box', function(e) {

// some action

});
4

2 回答 2

3

确切地说,这称为事件委托,它等待事件冒泡,然后根据选择器匹配事件。这更有效,因为只注册了一个处理程序,而不是元素数量的 N 倍。此外,您只需绑定一次,而不是每次更改动态内容。

$('#grid-container').on('mouseenter', '.grid-box', function(e) {

    // some action

}).on('mouseleave', '.grid-box', function(e) {

    // some action

});
于 2013-01-07T18:43:31.607 回答
1

选择器作为第二个参数仍然有效:

$('#grid-container').on({ ...}, '.grid-box');

http://jsfiddle.net/QkFTz/1/

另一种方法是单独绑定它们,我个人认为更清楚:

$("#grid-container").on('mouseenter', '.grid-box', function () {})
   .on('mouseleave', '.grid-box', 'function () {});
于 2013-01-07T18:44:26.440 回答