开发者

What is the correct syntax for `.live()` binding of the 'hover' method?

开发者 https://www.devze.com 2023-01-10 23:09 出处:网络
We call a 开发者_StackOverflow.live() method like this: $(\'.link\').live(\'click\', loadContent); But what about if I\'m binding to hover instead, which calls for two functions separated by a co

We call a 开发者_StackOverflow.live() method like this:

$('.link').live('click', loadContent);

But what about if I'm binding to hover instead, which calls for two functions separated by a comma? When I put in this:

$('.thumb.dim').live('hover', function(){$(this).removeClass('dim');}, function(){$(this).addClass('dim');});

The mouseenter event does trigger the first function above (removeClass('dim')), but on mouseleave nothing happens. Is there a correct way to write this?


live only takes one callback, but you can check the passed event information for the type of the callback:

$('.thumb.dim').live('hover', function(e) {
    if (e.type == 'mouseover') {
        $(this).removeClass('dim');
    } else {
        $(this).addClass('dim');
    }
});

Alternatively since you're just removing/adding a class, you can do;

$('.thumb.dim').live('hover', function(e) {
    $(this).toggleClass('dim');
});


Guess - I don't know how jQuery does this internally.

Could it be that the event doesn't get triggered because it's no longer dim? You could try adding a dim_disabled class or similar and a mouse-out event for dim_disabled to restore the dim?


Duh! The function is removing the class that triggers the function! Once the 'dim' class is removed on mouseenter, this no longer responds to a mouseout event!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号