0

我试图让我的 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');
})​
4

4 回答 4

2

您可以将两个函数传递给 jQuery hover - 一个用于 mousein,一个用于 mouseout。只要您没有动态添加的图像,就可以进行此更改。如果您正在淡出的元素具有 ID 或类,您的代码也会简单得多:

$('#image_layout img').hover(
    function () {
        $(this).closest('.someClass').fadeIn('fast');
    },
    function () {
        $(this).closest('.someClass').fadeOut('fast');
    }
);
于 2012-08-07T17:12:28.097 回答
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');
})

参考

于 2012-08-07T17:10:47.207 回答
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');
});
于 2012-08-07T17:10:54.183 回答
1

查看Douglas Crockford 的 JS 样式指南。他会让你的代码看起来像(有改进):

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,只需直接调用该函数即可。

于 2012-08-07T17:13:59.267 回答