javascript - 为什么悬停在委托(delegate)事件处理程序中不起作用?

标签 javascript jquery css hover

我正在动态添加一些元素并在委托(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 实际上不是事件,只是 mouseentermouseleave 的简写。来自docs :

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.

所以你不能用它来“委托(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/

相关文章:

javascript - 网站用户测试

Javascript:从另一个对象在javascript中创建一个深度嵌套的对象

javascript - 删除 2 个 div 之间的单个字符

页面没有焦点时javascript动画排队

javascript - 复选框:一次只允许单击一个复选框

javascript - 菜单的高度不正确 CSS

javascript - 在 JQuery/Backbone 中,如何重写每个 AJAX 请求以添加附加参数?

css - 插入 HTML 时平滑的边框增长过渡会导致它增长吗?

javascript - Bootstrap 特殊字符随机显示?

asp.net - 清除属性未按预期工作