Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/430.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将$(this)传递给jQuery.hover()函数_Javascript_Jquery_Hover_This_Scope - Fatal编程技术网

Javascript 将$(this)传递给jQuery.hover()函数

Javascript 将$(this)传递给jQuery.hover()函数,javascript,jquery,hover,this,scope,Javascript,Jquery,Hover,This,Scope,我编写了一个简单的工具提示功能,供大家查看 问题是,在.hover()中设置的两个处理程序函数中,我需要访问$(this)和基于它的其他两个变量。为了实现这一点,我在两个处理程序中声明了相同的3个变量: $('a').hover( function () { var $this = $(this); var link_offset = $this.offset(); var link_tooltip = $this.data('toolti

我编写了一个简单的工具提示功能,供大家查看

问题是,在
.hover()
中设置的两个处理程序函数中,我需要访问
$(this)
和基于它的其他两个变量。为了实现这一点,我在两个处理程序中声明了相同的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实现这一点?

在匿名回调中调用一个命名函数:

$('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 
    };
}

如果确实需要,可以直接分配
mouseenter()
mouseleave()
事件处理程序,并通过设置这些值的自定义函数路由调用。但它真的需要吗?更新了答案并添加了一个提琴