我想知道jQuery的“ this”是否可以简化我的代码?

完整代码在这里
http://bootsnipp.com/snippets/7ORr

感谢您的帮助,任何建议表示赞赏。

jQuery代码

/*
Ref: http://api.jquery.com/hover/
Calling $( selector ).hover( handlerIn, handlerOut ) is shorthand for:
$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );
*/

$(document).ready(function() {

    $('.fd-fade1').hover(function() {
        // img1
        $('img.fd-img1').fadeIn('slow');
    },
    function() {
        $("img.fd-img1").fadeOut("slow");
    });

    // img2
    $('.fd-fade2').hover(function() {
        $('img.fd-img2').fadeIn('slow');
    },
    function() {
        $("img.fd-img2").fadeOut("slow");
    });

    // img3
    $('.fd-fade3').hover(function() {
        $('img.fd-img3').fadeIn('slow');
    },
    function() {
        $("img.fd-img3").fadeOut("slow");
    });

}); // end document.ready function

最佳答案

是的,您当然可以使用this压缩代码。例如,如果您将.fading类添加到要淡入/淡出的图像的所有父<div>元素中,则每个HTML的HTML外观应如下所示:

<div class="fd-fade1 fading">
    <img src="http://i.imgur.com/yxAxCaK.jpg" class="fd-img1" alt="">
</div>


然后,通过将回调的上下文与hover()结合使用,您只需在JavaScript中使用一组this回调即可实现颜色淡入效果:

$(document).ready(function () {
    $('.fading').hover(function () {
        $(this).children("img").fadeIn('slow');
    }, function () {
        $(this).children("img").fadeOut("slow");
    });
});


这是JSFiddle来演示实际代码。

哦,对了,如果您想停止淡入淡出的链接(不确定是否注意到了这种情况),则可以在淡入淡出之前使用jQuery的stop(),如下所示:

$(this).children("img").stop().fadeIn('slow');
$(this).children("img").stop().fadeOut("slow");


希望这可以帮助!如果您有任何问题,请告诉我。

07-24 09:46
查看更多