jquery:在hover()函数中传递变量?

lau*_*kok 6 variables jquery scope global-variables hover

我可以在hover()中传递变量吗?

如下面的脚本,我不想两次声明相同的变量var target = xxx,我不想让这个变量成为全局target = xxxbcos我有其他函数使用这个变量名称 - 目标.

   $('.image-profile').hover(function () {

        var target = $('.button-change-image-profile',this);
        target.show();

    },function () {

        //var target = $('.button-change-image-profile',this);
        target.hide();

    });
Run Code Online (Sandbox Code Playgroud)

So I tried to pass the var like this },function (target) {, of course it is wrong, but any other method to pass this var?

thanks.

Nic*_*ver 7

简短的版本只是在这里切换:

$('.image-profile').hover(function () {
    $('.button-change-image-profile',this).toggle();
});
Run Code Online (Sandbox Code Playgroud)

为了让它在每个处理程序中可用(作为一种更通用的解决方案),在循环(.each()例如使用)时将其定义为外部,如下所示:

$('.image-profile').each(function() {
    var target = $('.button-change-image-profile',this);
    $(this).hover(function () {
        target.show();
    },function () {
        target.hide();
    });
});
Run Code Online (Sandbox Code Playgroud)


小智 7

另一种可能的方法:this使用jQuery 将数据保存到悬停/输出中.data().您将它保存在鼠标中,在鼠标输出时检索它.这可能在概念上类似于使用全局变量或变换悬停函数,因此,t可能会产生一些垃圾......

$('.image-profile').hover(function () {

  var target = $('.button-change-image-profile',this);
  target.show();

  // we save the target object into the 'target' key.
  $(this).data('target',target);  

},function () {

  // we retrieve the target object (a jQuery object) and then hide it.
  $(this).data('target').hide();

});
Run Code Online (Sandbox Code Playgroud)

希望这种方法不是太错了......