我试图让我的jquery代码看起来更好。我的功能正常,但我想知道是否有人可以让我的代码不那么难看。非常感谢!
HTML
<div class='image_layout'>
<a href='#'><img src=' a.jpg '/></a>
<br><p class='credits'>hahahah
<br>Agency: Agency1
<br>Picture ID: 5 </p>
</div>
的jQuery
$('#image_layout').on('hover', 'img', function() {
$(this).parent().next().next().fadeIn('fast');
})
$('#image_layout').on('mouseout', 'img', function() {
$(this).parent().next().next().fadeOut('fast');
})
答案 0 :(得分:2)
你可以将两个函数传递给jQuery hover - 一个用于mousein,一个用于mouseout。只要您没有动态添加的图像,就可以进行此更改。如果您要淡化的元素具有ID或类,则您的代码也会更简单:
$('#image_layout img').hover(
function () {
$(this).closest('.someClass').fadeIn('fast');
},
function () {
$(this).closest('.someClass').fadeOut('fast');
}
);
答案 1 :(得分:1)
我会使用.eq
而不是两个next
语句,此外,hover有两个函数,第一个用于mouseenter
事件,第二个用于mouseout
$('#image_layout').hover('hover', 'img', function () {
$(this).parent().eq(2).fadeIn('fast');
}, function () {
$(this).parent().eq(2).fadeOut('fast');
})
<强>参考强>
答案 2 :(得分:1)
$('.image_layout').on('hover', 'img', function (e) {
if(e.type == 'mouseover') {
$(this).closest('.image_layout').find('.credits').stop().fadeIn('fast');
} else {
$(this).closest('.image_layout').find('.credits').stop().fadeOut('fast');
}
})
你也可以做到:
$('.image_layout').on('hover', 'img', function() {
$(this).closest('.image_layout').find('.credits').stop().fadeIn('fast');
}, function() {
$(this).closest('.image_layout').find('.credits').stop().fadeOut('fast');
});
如果你确定除了悬停图像之外什么都不会导致元素褪色,你可以简单地写一下:
$('.image_layout').on('hover', 'img', function() {
$(this).closest('.image_layout').find('.credits').stop().fadeToggle('fast');
});
答案 3 :(得分:1)
查看Douglas Crockford's JS Style Guide。他会让你的代码看起来像(有改进):
var obj = $('#image_layout img');
obj.mouseover( function(){
$(this).parent([selector]).next([selector]).fadeIn('fast');
});
obj.mouseout( function(){
$(this).parent([selector]).next([selector]).fadeOut('fast');
});
您不需要on
,只需直接调用该函数。