jquery: passing variables in hover() function?

2019-04-08 01:35发布

Can I pass a variable in hover()?

As in the script below, I don't want to declare the same variable twice var target = xxx and I don't want to make this variable a global target = xxx bcos I have other function using this variable name - target.

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

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

    },function () {

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

    });

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.

4条回答
等我变得足够好
2楼-- · 2019-04-08 02:13

Just define var out of hover function.

查看更多
Deceive 欺骗
3楼-- · 2019-04-08 02:21

Another possible approach: to save data into the this of the hover in/out using jQuery .data(). You save it on mouse in, you retrieve it on mouse out. This may be conceptually similar to use a global var or a var out of hover function, thus, t may create some garbage...

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

});

Hopefully, this approach isn't too wrong...

查看更多
forever°为你锁心
4楼-- · 2019-04-08 02:30

I think jQuery bind might be what you want.

查看更多
我只想做你的唯一
5楼-- · 2019-04-08 02:35

The short version is just to toggle here:

$('.image-profile').hover(function () {
    $('.button-change-image-profile',this).toggle();
});

To have it available in each handler (as a more general solution) define it outside when looping (using .each() for example), like this:

$('.image-profile').each(function() {
    var target = $('.button-change-image-profile',this);
    $(this).hover(function () {
        target.show();
    },function () {
        target.hide();
    });
});
查看更多
登录 后发表回答