为什么悬停在委派的事件处理程序中不起作用?

时间:2016-01-25 11:19:05

标签: javascript jquery css hover

我正在动态添加一些元素,并在委托的事件处理程序中为它分配一个悬停属性,我在下面的代码中使用了它,但它没有用。

$(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却不行。

1 个答案:

答案 0 :(得分:6)

功能/事件.hover实际上不是一个事件,而只是mouseentermouseleave的简写。来自docs

  

.hover()方法会为mouseentermouseleave事件绑定处理程序。您可以使用它在鼠标位于元素中时简单地将行为应用于元素。

所以你不能用它来“委派”事件。

<强>解决方案

正如您已经提到的那样,正如文档中提到的那样,您可以使用:

$(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
  }
});
相关问题