Jquery在Ajax加载后无法使用hover的问题

10

我遇到了一个问题,我的hover事件在ajax加载后不起作用,只有在页面初始加载时才起作用...这是我目前正在使用的代码:

    $(".table tbody tr").hover(
        function () {
            $(this).children('td').children('.operation').children('.btn-group').fadeIn();
        },
        function () {
            $(this).children('td').children('.operation').children('.btn-group').fadeOut();
        }
    );

我知道我需要使用$(document).on()作为选择器,但我不确定如何正确地使用原始代码中的功能。任何帮助都将不胜感激。

1个回答

22

解决方案

这是来自comments的原创解决方案。确实,必须使用document(或任何不受ajax调用影响的祖先元素)。

$(document).on({
    mouseenter: function () {
        $(this).find('.btn-group').fadeIn();
    },
    mouseleave: function () {
        $(this).find('.btn-group').fadeOut();
    }
}, '.table tbody tr');

原始

$(".table tbody").on("hover","tr",
    function () {
        $(this).children('td').children('.operation').children('.btn-group').fadeIn();
    },
    function () {
        $(this).children('td').children('.operation').children('.btn-group').fadeOut();
    }
);

编辑

确实,hover已经过时,在这种情况下可能不起作用!试试这个:

$(".table tbody").on({
    mouseenter: function () {
        $(this).children('td').children('.operation').children('.btn-group').fadeIn();
    },
    mouseleave: function () {
        $(this).children('td').children('.operation').children('.btn-group').fadeOut();
    }
},'tr');

我不确定你在做什么,但这种方法甚至可能更短:

$(".table tbody").on({
    mouseenter: function () {
        $(this).find('.btn-group').fadeIn();
    },
    mouseleave: function () {
        $(this).find('.btn-group').fadeOut();
    }
},'tr');

1
注意,“hover”伪事件在jQuery 1.9中不再受支持。http://jquery.com/upgrade-guide/1.9/#hover-pseudo-event 也可以将其视为一个机会,使代码与未来版本的jQuery兼容。 - Kevin B
嗨,安德鲁。这似乎会在初始页面加载和ajax刷新后完全停止代码工作。我尝试在两个函数中添加警报,但它们在TR悬停时也不会出现。 - Danny Brady
嗨,安德鲁,非常感谢您的贡献和更简洁的解决方案。但在通过Ajax加载表格内容后,我仍然遇到了一些问题。 - Danny Brady
$(document).on({ mouseenter: function () { $(this).find('.btn-group').fadeIn(); }, mouseleave: function () { $(this).find('.btn-group').fadeOut(); } }, '.table tbody tr'); 在玩弄您的代码后,这最终成为了可行的解决方案,非常感谢。 - Danny Brady
上帝的工作。我绕过网站规则只是为了说这句话。安德鲁,你值得拥有不仅仅是一枚金牌。 - Rum Jeremy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接