2014-09-04 76 views
4

我写了一个简单的工具提示功能,可以看到here

事情是,在.hover()设置的两个处理函数中,我需要访问$(this)和其他2个基于它的变量。为了做到做到这一点,我声明相同的3个变量在这两个处理程序:

$('a').hover(
    function() { 
     var $this = $(this); 
     var link_offset = $this.offset(); 
     var link_tooltip = $this.data('tooltip'); 
     // Rest of the code 
    }, 
    function() { 
     var $this = $(this); 
     var link_offset = $this.offset(); 
     var link_tooltip = $this.data('tooltip'); 
     // Rest of the code 
    } 
); 

DRY原则应得到尊重,所以我的问题是:通过设置为相同的变量是否有其他更聪明的/不太脏的方式这两个函数在.hover()

有意思的是,变量不能是全局变量(而且全局变量也是邪恶的)。

任何想法如何实现这与jQuery或纯JS?

+1

如果你真的必须,你可以指定'的mouseenter()'和'鼠标离开()直接'事件处理程序和路由通过设置这些值的自定义函数调用。但它真的需要吗? – Kami 2014-09-04 21:55:23

回答

7

呼叫匿名回调里面一个命名函数:

$('a').hover(function() { 
     hoverFunc($(this), true) 
    }, function() { 
     hoverFunc($(this), false) 
    }); 

function hoverFunc($this, is_hovered) { 
    var link_offset = $this.offset(); 
    var link_tooltip = $this.data('tooltip'); 
    if (is_hovered) { 
     console.log('ok') 
     // do something 
    } else { 
     console.log('out') 
     // do something else 
    }; 
} 

http://jsfiddle.net/mblase75/8njk2m32/

+0

当然!简单而甜蜜。非常感谢。 – lesssugar 2014-09-04 21:59:00

+1

更新的答案并添加了一个小提琴 – Blazemonger 2014-09-04 22:02:14