jQuery on('hover')事件替换

Wil*_*azi 1 jquery jquery-hover jquery-on

我想在悬停时交换一个img src.通常我会使用:

$('#img').hover(function() {
    $(this).attr('src', 'http://www.example.com/new-img.jpg');
});
Run Code Online (Sandbox Code Playgroud)

但是,我正在通过Ajax加载内容,所以通常我会使用:

$('#main').on('hover', '#img', function() {
    $('#img').attr('src', 'http://www.example.com/new-img.jpg');
});
Run Code Online (Sandbox Code Playgroud)

但我正在阅读('hover',...)在jQuery 1.8中被弃用并在1.9中被删除(jQuery Docs))中,这是我目前正在使用的.除了使用以外,有没有人有任何工作:

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

$('#main').on('mouseleave', '#img', function() {
   $('#img').attr('src', 'http://www.example.com/old-img.jpg');
});
Run Code Online (Sandbox Code Playgroud)

Sha*_*dow 7

您可以应用多个事件,然后event.type像这样检查:

$('#main').on('mouseenter mouseleave', '#img', function(e) {
    $(this).attr('src', 'http://www.example.com/' + (e.type == 'moseenter' ? 'new-img.jpg' : 'old-img.jpg'));
});
Run Code Online (Sandbox Code Playgroud)

js小提琴

您还可以使用switch-caseif/else

$('#main').on('mouseenter mouseleave', '#img', function(e) {
    switch(e.type) {
        case 'mouseenter':
            $(this).attr('src', 'http://www.example.com/new-img.jpg');
            break;
        case 'mouseleave':
            $(this).attr('src', 'http://www.example.com/old-img.jpg');
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)


lon*_*day 6

不,你需要在两个电话中完成.但是对于添加的jQuery点,你可以链接它们:

$('#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');
});
Run Code Online (Sandbox Code Playgroud)

正如本杰明在下面评论的那样,你可以进一步优化(这次你会获得普通的旧Javascript点数):

$('#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';
});
Run Code Online (Sandbox Code Playgroud)

  • @kmfk但这种方式不支持事件委托."我正在通过Ajax加载内容" (3认同)
  • @BenjaminGruenbaum确实是`this.src`.谢谢:补充道. (2认同)