.hover(…) and on.(“hover”…) behaving differently

两盒软妹~` 提交于 2020-01-01 05:30:16

问题


Using JQuery I am trying to chain a couple of functions when an element has a hover state.

I would normally use the .hover event function, but after reading some tutorials I read that using .on is better as you can use one event handler to monitor all bubbling events within a document.

However, I am having problems when I chain two functions together like so:

$("element").on( "hover", function() {         
    console.log("one");     
}, function() {         
    console.log("two");     
});

I expected the result to be one two (which was the case when using .hover) but instead I get two two.

Can anyone explain what I am doing wrong or whether this is expected behaviour and why?

Reproduced using .hover(...): http://jsfiddle.net/gXSdG/

Reproduced using .on(hover...): http://jsfiddle.net/gXSdG/1/


回答1:


.on() can only take 1 function, so you have to interrogate the passed event to check what the event was. Try this:

$("element").on("hover", function(e) {
    if (e.type == "mouseenter") {
        console.log("one");   
    }
    else { // mouseleave
        console.log("two");   
    }
});

Example fiddle

Alternatively you can split the two events which constitute the hover() method - mouseenter and mouseleave:

$("#element").on("mouseenter", function() {
  console.log("one");   
}).on('mouseleave', function() {
  console.log("two");   
});
#element {
  background-color: black;
  height: 100px;
  margin: 100px;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>



回答2:


You've just confused about what was happening in the first place, there is no function chaining in either of your examples. The APIs for hover and on are different, read them carefully, and here's an overview as it pertains to your problem:

hover takes either one or two arguments, both functions. The first is run when the mouse enters, the second when the mouse leaves.

on takes only one callback, and your first function is never used, since it's used for a different parameter, and the second one is used as the callback and called for all hover events, that is, mouse enter and mouse leave.



来源:https://stackoverflow.com/questions/10789554/hover-and-on-hover-behaving-differently

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!