jQuery on('hover') Event Replacement

后端 未结 3 1677
难免孤独
难免孤独 2021-01-22 07:35

I\'m looking to swap an img src on hover. Typically I would use:

$(\'#img\').hover(function() {
    $(this).attr(\'src\', \'http://www.example.com/new-img.jpg\'         


        
3条回答
  •  醉酒成梦
    2021-01-22 07:49

    No, you'll need to do it in two calls. But for added jQuery points, you can chain them:

    $('#main').on('mouseenter', '#img', function() {
       $('#img').attr('src', 'http://www.example.com/new-img.jpg');
    }).on('mouseleave', '#img', function() {
       $('#img').attr('src', 'http://www.example.com/old-img.jpg');
    });
    

    And as Benjamin comments below, you can optimise further (you get plain old Javascript points this time):

    $('#main').on('mouseenter', '#img', function() {
       this.src = 'http://www.example.com/new-img.jpg';
    }).on('mouseleave', '#img', function() {
       this.src = 'http://www.example.com/old-img.jpg';
    });
    

提交回复
热议问题