jquery中取消和绑定hover事件的正确方式
2015-07-15 16:53
591 查看
在网页设计中,我们经常使用jquery去响应鼠标的hover事件,和mouseover和mouseout事件有相同的效果,但是这其中其中如何使用on去绑定hover方法呢?如何用off取消绑定的事件呢?
一、如何绑定hover事件
先看以下代码,假设我们给a标签绑定一个click和hover事件:
$(document).ready(function(){ $('a').on({ hover: function(e) {
//Hover event handler
alert("hover"); },
click: function(e) { // Click event handler
alert("click"); } });
});
当点击a标签的时候,奇怪的事情发生了,其中绑定的hover事件完全没有反应,绑定的click事件却可以正常响应。
但是如果换一种写法,比如:
$("a").hover(function(){ alert('mouseover'); }, function(){
alert('mouseout'); })
应该使用 mouseenter 和 mouseleave 这两个事件来代替,(这也是 .hover() 函数中使用的事件)
所以完全可以直接像这样来引用:
$(document).ready(function(){ $('a').on({ mouseenter: function(e) {
//Hover event handler
alert("mouseover"); }, mouseleave: function(e) {
//Hover event handler
alert("mouseout"); }, click: function(e) {
// Clickevent handler
alert("click"); } });
});
因为.hover()是jQuery自己定义的事件,是为了方便用户绑定调用mouseenter和mouseleave事件而已,它并非一个真正的事件,所以当然不能当做.on()中的事件参数来调用。
二、如何取消hover事件
大家都知道,可以使用off函数去取消绑定的事件,但是只能取消通过bind绑定的事件,jquery中的hover事件是比较特殊的,如果通过这种方式去绑定的事件,则无法取消。
$("a").hover(function(){ alert('mouseover'); }, function(){
alert('mouseout'); })
取消绑定的hover事件的正确方式:
$('a').off('mouseenter').unbind('mouseleave');
一、如何绑定hover事件
先看以下代码,假设我们给a标签绑定一个click和hover事件:
$(document).ready(function(){ $('a').on({ hover: function(e) {
//Hover event handler
alert("hover"); },
click: function(e) { // Click event handler
alert("click"); } });
});
当点击a标签的时候,奇怪的事情发生了,其中绑定的hover事件完全没有反应,绑定的click事件却可以正常响应。
但是如果换一种写法,比如:
$("a").hover(function(){ alert('mouseover'); }, function(){
alert('mouseout'); })
应该使用 mouseenter 和 mouseleave 这两个事件来代替,(这也是 .hover() 函数中使用的事件)
所以完全可以直接像这样来引用:
$(document).ready(function(){ $('a').on({ mouseenter: function(e) {
//Hover event handler
alert("mouseover"); }, mouseleave: function(e) {
//Hover event handler
alert("mouseout"); }, click: function(e) {
// Clickevent handler
alert("click"); } });
});
因为.hover()是jQuery自己定义的事件,是为了方便用户绑定调用mouseenter和mouseleave事件而已,它并非一个真正的事件,所以当然不能当做.on()中的事件参数来调用。
二、如何取消hover事件
大家都知道,可以使用off函数去取消绑定的事件,但是只能取消通过bind绑定的事件,jquery中的hover事件是比较特殊的,如果通过这种方式去绑定的事件,则无法取消。
$("a").hover(function(){ alert('mouseover'); }, function(){
alert('mouseout'); })
取消绑定的hover事件的正确方式:
$('a').off('mouseenter').unbind('mouseleave');
相关文章推荐
- jQuery--工具函数
- JavaScript封装Ajax(类JQuery中$.ajax()方法)
- 超炫的时间轴jquery插件Timeline Portfolio
- jQuery 鼠标滚轮插件 jquery.mousewheel.js
- jQuery each,避免使用js for循环
- jquery 选择器
- jQuery siblings() 的作用
- jQuery使用FormData上传文件
- jquery ajax 全介绍
- jQuery一些笔记
- jquery 获取滚动条高度
- jquery 选择器(name,属性,元素)大全
- Jquery操作select
- 基于jQuery的AJAX和JSON的实例
- Jquery中ul li循环取值方式
- jQuery插件
- JQuery基础选择器
- jQuery图表插件Flot中文文档
- 基于jquery的秒表倒计时
- 全屏背景:15个jQuery插件实现全屏背景图像或媒体