.hover(...)和on。(“悬停”...)的行为不同 [英] .hover(...) and on.("hover"...) behaving differently

查看:161
本文介绍了.hover(...)和on。(“悬停”...)的行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JQuery我试图在元素具有悬停状态时链接几个函数。



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



然而,当我将两个函数链接在一起时,我遇到了问题:

 ()
console.log(one);
},function(){
console.log(two);
});

我预计结果是一两个 在使用 .hover 的情况下,我得到了两个



任何人都可以解释我做错了什么,或者这是否是预期的行为,为什么? 使用 .hover(。 ..) http://jsfiddle.net/gXSdG/



使用 .on(hover ...)转载 http://jsfiddle.net/gXSdG/1/

.on()只能使用1个函数,因此您必须询问传入的事件来检查事件是什么。试试这个:

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

示例小提琴



或者,您可以拆分构成 hover() 方法 - mouseenter mouseleave



()(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>


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/

解决方案

.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>

这篇关于.hover(...)和on。(“悬停”...)的行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆