jQuery on('hover')事件替换 [英] jQuery on('hover') Event Replacement
问题描述
我希望在悬停时交换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屋!