使用setTimeout切换图像

时间:2014-07-02 08:05:34

标签: jquery

点击后我试图更改一些图像。 最初我有一个名为let的说图像image1。点击后我想将其更改为:image2。 问题是在1秒后,我想再次回到初始图像(图像1)。

我的代码如下:

    <script>
$(window).load(function() {

    $('#rounded-corner #mtg_card').click(function()
        {
            $(this).find(".mtg_shop_cart").attr("src","image1");
            window.setTimeout(function() {
              $(this).find(".mtg_shop_cart").attr("src","image2");
            }, 1000);
            return false;
        });
});

</script>

1 个答案:

答案 0 :(得分:0)

您需要在其他变量中缓存this,然后在setTimeout函数中使用该变量

使用

$(window).load(function () {
    $('#rounded-corner #mtg_card').click(function () {
        $(this).find(".mtg_shop_cart").prop("src", "image1");
        var self = this; //Cache this in a variable
        window.setTimeout(function () {
            $(self).find(".mtg_shop_cart").prop("src", "image2"); //Use cached variable here
        }, 1000);
        return false;
    });
});

优雅的方法是使用.bind(this)

$(window).load(function () {
    $('#rounded-corner #mtg_card').click(function () {
        $(this).find(".mtg_shop_cart").attr("src", "image1");
        window.setTimeout(function () {
            $(this).find(".mtg_shop_cart").attr("src", "image2");
        }.bind(this), 1000); //Here use .bind(this)
        return false;
    });
});
相关问题