.hover(...) 和 on.(“hover"...) 行为不同不同、行为、hover、on

2023-09-07 22:54:22 作者:转角遇到狗

当元素处于悬停状态时,我尝试使用 JQuery 链接几个函数.

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

我通常会使用 .hover 事件函数,但在阅读了一些教程后,我了解到使用 .on 更好,因为您可以使用一个事件处理程序来监控所有文档中的冒泡事件.

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

我希望结果是 一二 (使用 .hover 时就是这种情况) 但我得到的是 二两个.

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?

使用 .hover(...) 复制:http://jsfiddle.net/gXSdG/

使用 .on(hover...) 复制:http://jsfiddle.net/gXSdG/1/

推荐答案

.on() 只能带 1 个函数,所以要查询传递的 event 到检查事件是什么.试试这个:

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

小提琴示例

或者,您可以拆分构成 hover() 方法的两个事件 - mouseentermouseleave:

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>