2014-09-04 107 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