我正在动态添加一些元素并在委托(delegate)事件处理程序中为其分配一个悬停属性,我在下面的代码中使用了它,但它不起作用。
$(document).on("hover", ".sec_close_fast", function() {
$(this).parent('div').parent('div').css("border", "3px solid #000000");
});
然后我使用 mouseover
并且它起作用了:
$(document).on("mouseover", ".sec_close_fast", function() {
$(this).parent('div').parent('div').css("border", "3px solid #000000");
});
我想知道为什么 hover
不起作用,而 mouseover
却起作用。
最佳答案
函数/事件 .hover
实际上不是事件,只是 mouseenter
和 mouseleave
的简写。来自docs :
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.
所以你不能用它来“委托(delegate)”事件。
解决方案
正如您已经提到的以及文档中提到的那样,您可以使用:
$(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
}
});
关于javascript - 为什么悬停在委托(delegate)事件处理程序中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34991316/