Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

javascript - 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");
});

Then I used mouseover and it worked:

$(document).on("mouseover", ".sec_close_fast", function() {
  $(this).parent('div').parent('div').css("border", "3px solid #000000");
});

I would like to know why hover does not work, yet mouseover does.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The function / event .hover is not actually an event, but just a shorthand for mouseenter and mouseleave. From the 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.

So you cannot use it to "delegate" events.

Solution

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
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...