jQuery on('hover')事件替换 [英] jQuery on('hover') Event Replacement

查看:316
本文介绍了jQuery on('hover')事件替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在悬停时交换img src.通常,我会使用:

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');
});

但是,我通过Ajax加载内容,因此通常我会使用:

However, I'm loading the content in via Ajax so normally I would use:

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

但是我正在阅读on('hover',...)在jQuery 1.8中已弃用,在1.9中已删除(

But I'm reading that on('hover', ...) was deprecated in jQuery 1.8 and removed in 1.9 (jQuery Docs), which is what I'm currently using. Do anyone have any work arounds other than using:

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

推荐答案

否,您需要在两次调用中进行此操作.但是,对于添加的jQuery点,您可以将它们链接起来:

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');
});

正如本杰明(Benjamin)在下面的评论中,您可以进一步优化(这次您得到了简单的旧Java脚本点):

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';
});

这篇关于jQuery on('hover')事件替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆