动态添加类后,jQuery 悬停处理程序功能无法处理取消悬停 [英] jQuery hover handler function not working on unhover after dynamically adding a class
问题描述
根据我的研究,我认为以下代码应该可以工作.
From my research i believe that the following code should work.
我正在使用 jquery 将图像动态添加到页面,jquery 从 JSON 文件中提取这些图像.出于这个原因,我需要使用 jQuery 的 on() 方法来允许这个悬停工作.
I am dynamically adding images to a page using jquery, which pulls these images from a JSON file. For this reason I need to use jQuery's on() method to allow this hover to work.
我正在遵循 jquery 文档中的指导——参见此处.
I am following the guidance in the jquery docs -- see here.
$(document).on('hover', ".portrait-image", function() {
console.log('hi');
}, function () {
console.log('bye');
});
这段代码反复显示bye
,而从不记录hi
.
This code repeatedly shows bye
while never logging hi
.
推荐答案
hover
不是您可以与 on
一起使用的事件.它只是事件 mouseenter
和 mouseleave
的简写.因此,您必须为您的代表团使用正确的名称.
hover
is not an event you can use with on
. It is only a shorthand for the events mouseenter
and mouseleave
. So you have to use them with the correct names for your delegation.
来自文档:
.hover() 方法绑定了 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.
所以像这样重写你的监听器:
So rewrite your listener like this:
$(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
:
就像在文档中看到的那样,on
最多有四个参数.最后两个是data
和handler
.您的 hi
回调被解释为 data
并且将被忽略.handler
是处理程序的实际 bye
回调.
Like seen in the documentation, on
has up to four parameters. The last two are data
and handler
. Your hi
callback is interpreted as data
and will be ignored. The handler
is the actual bye
callback for the handler.
hover
是 jQuery 中的一个伪名称.它会做这样的事情:
hover
is a pseudo name in jQuery. It will do something like this:
$(document).on('mouseenter mouseleave', '.portrait-image', function() {
console.log('hi');
});
这意味着每次你enter
OR leave
,它都会打印bye
.
This means every time you enter
OR leave
, it will print bye
.
这篇关于动态添加类后,jQuery 悬停处理程序功能无法处理取消悬停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!