Why hover does not work in delegated event handlers?(为什么悬停在委托事件处理程序中不起作用?)
问题描述
我正在动态添加一些元素并在委托事件处理程序中为其分配悬停属性,我在下面的代码中使用了该属性,但它不起作用.
I am adding some elements dynamically and assigning a hover property to it in delegated event handlers for which I used below code and it did not work.
$(document).on("hover", ".sec_close_fast", function() {
$(this).parent('div').parent('div').css("border", "3px solid #000000");
});
然后我使用 mouseover
并且成功了:
Then I used mouseover
and it worked:
$(document).on("mouseover", ".sec_close_fast", function() {
$(this).parent('div').parent('div').css("border", "3px solid #000000");
});
我想知道为什么 hover
不起作用,而 mouseover
起作用.
I would like to know why hover
does not work, yet mouseover
does.
推荐答案
函数/事件 .hover
实际上并不是一个事件,而只是 mouseenter
的简写和鼠标离开
.来自 docs:
The function / event .hover
is not actually an event, but just a shorthand for mouseenter
and mouseleave
. From the docs:
.hover()
方法绑定 mouseenter
和 mouseleave
事件的处理程序.您可以使用它在鼠标位于元素内时简单地将行为应用于元素.
The
.hover()
method binds handlers for bothmouseenter
andmouseleave
events. You can use it to simply apply behavior to an element during the time the mouse is within the element.
所以你不能用它来委托"事件.
So you cannot use it to "delegate" events.
解决方案
正如您已经提到的以及文档中提到的那样,您可以使用:
As you have already mentioned and as it is mentioned in the docs, you can use:
$(static_parent).on("mouseenter mouseleave", element, function (e) {
if (e.type == "mouseenter") {
// check if it is mouseenter, do something
} else {
// if not, mouseleave, do something
}
});
这篇关于为什么悬停在委托事件处理程序中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么悬停在委托事件处理程序中不起作用?
基础教程推荐
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01