根据我的研究,我相信以下代码应该有效。
我使用 jquery 将图像动态添加到页面,它从 JSON 文件中提取这些图像。为此,我需要使用 jQuery 的 on()允许此悬停工作的方法。
我遵循 jquery 文档中的指导 -- see here .
$(document).on('hover', ".portrait-image", function() {
console.log('hi');
}, function () {
console.log('bye');
});
此代码重复显示 bye
而从不记录 hi
。
hover
不是可以与 on
一起使用的事件。它只是事件 mouseenter
和 mouseleave
的简写。因此,您必须为您的代表团使用正确的名称。
来自文档:
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
最多有四个参数。最后两个是data
和handler
。您的 hi
回调被解释为 data
并将被忽略。 handler
是处理程序的实际 bye
回调。
hover
是 jQuery 中的伪名称。它会做这样的事情:
$(document).on('mouseenter mouseleave', '.portrait-image', function() {
console.log('hi');
});
这意味着每次您进入
或离开
时,它都会打印bye
。