javascript - jQuery 悬停处理函数在动态添加类后无法在悬停上工作

标签 javascript jquery hover

<分区>

根据我的研究,我相信以下代码应该有效。

我使用 jquery 将图像动态添加到页面,它从 JSON 文件中提取这些图像。为此,我需要使用 jQuery 的 on()允许此悬停工作的方法。

我遵循 jquery 文档中的指导 -- see here .

$(document).on('hover', ".portrait-image", function() {
    console.log('hi');
}, function () {
    console.log('bye');
});

此代码重复显示 bye 而从不记录 hi

最佳答案

hover 不是可以与 on 一起使用的事件。它只是事件 mouseentermouseleave 的简写。因此,您必须为您的代表团使用正确的名称。

来自文档:

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

所以像这样重写你的监听器:

$(document).on('mouseenter', '.portrait-image', function() {
    console.log('hi');
});

$(document).on('mouseleave', '.portrait-image', function() {
    console.log('bye');
});

或者像这样:

$(document).on({
    'mouseenter': function() {
        console.log('hi');
    },
    'mouseleave' function() {
        console.log('bye');
    }
}, '.portrait-image');

解释为什么只显示bye:

就像在 documentation 中看到的那样, on 最多有四个参数。最后两个是datahandler。您的 hi 回调被解释为 data 并将被忽略。 handler 是处理程序的实际 bye 回调。

hover 是 jQuery 中的伪名称。它会做这样的事情:

$(document).on('mouseenter mouseleave', '.portrait-image', function() {
    console.log('hi');
});

这意味着每次您进入离开时,它都会打印bye

关于javascript - jQuery 悬停处理函数在动态添加类后无法在悬停上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38611101/

相关文章:

javascript - Angular UI Bootstrap 日期选择器结合 UI.Mask

javascript - 如何使用 SweetAlert2 重置 CKeditor4

javascript - 检查背景中的特定图像

html - 链接没有悬停

javascript - 表示正则表达式中的任意一组字符

javascript - CFG/PEG 用于代码完成?

javascript - 使用特定的 JSON 数组填充 Chart.js

javascript - jQuery.parseHTML 的反向

jquery - 下拉菜单延迟不起作用

jquery - 使用 :hover states 按下按钮时禁用 iOS 的行为