Javascript 动态添加类后,jQuery悬停处理程序函数无法在取消悬停上工作
根据我的研究,我相信下面的代码应该可以工作 我使用jquery动态地向页面添加图像,jquery从JSON文件中提取这些图像。出于这个原因,我需要使用jQuery的方法来允许这个悬停运行 我遵循jquery文档中的指导--Javascript 动态添加类后,jQuery悬停处理程序函数无法在取消悬停上工作,javascript,jquery,hover,Javascript,Jquery,Hover,根据我的研究,我相信下面的代码应该可以工作 我使用jquery动态地向页面添加图像,jquery从JSON文件中提取这些图像。出于这个原因,我需要使用jQuery的方法来允许这个悬停运行 我遵循jquery文档中的指导-- 此代码重复显示bye,但从不记录hi悬停不是一个可与on一起使用的事件。它只是事件mouseenter和mouseleave的简写。因此,您必须为您的代表团使用正确的名称 从文件中可以看出: .hover()方法绑定mouseenter和mouseleave的处理程序 事件。
此代码重复显示
bye
,但从不记录hi
悬停
不是一个可与on
一起使用的事件。它只是事件mouseenter
和mouseleave
的简写。因此,您必须为您的代表团使用正确的名称
从文件中可以看出:
.hover()方法绑定mouseenter和mouseleave的处理程序
事件。您可以使用它来简单地将行为应用到元素
鼠标在元素内的时间
因此,请像这样重写您的听众:
$(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');
$(document).on('mouseenter mouseleave', '.portrait-image', function() {
console.log('hi');
});
或者像这样:
$(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');
$(document).on('mouseenter mouseleave', '.portrait-image', function() {
console.log('hi');
});
解释为什么只显示
bye
:
如中所示,上的最多有四个参数。最后两个是数据
和处理程序
。您的hi
回调被解释为data
,将被忽略。handler
是处理程序的实际bye
回调
hover
是jQuery中的一个伪名称。它将执行以下操作:
$(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');
$(document).on('mouseenter mouseleave', '.portrait-image', function() {
console.log('hi');
});
这意味着每次您进入
或离开
,它都会打印再见
@VisioN它肯定是在记录“再见”
。此外,您知道委派的事件可以分组吗?例如:$(document).on({mouseenter:…,mouseleave:…},.crative image')
。请参阅我编辑的答案@phantom@大卫,这个例子是错误的。请再读一遍这个问题。@VisioN,是的,我知道这个符号。但是我不喜欢这种风格。但为了完整,我添加了它。。。谢谢