使用setTimeout重新加载图像

时间:2014-11-07 20:59:17

标签: javascript jquery html settimeout

当我加载图片并加载失败时,我尝试使用setTimeout延迟后重新加载,如下所示:

$('img').error(function(){
    setTimeout(function(){
        $(this).attr('src', $(this).attr('src') + '?' + Math.random());
    }, 3000);
});

但是此解决方案不会按预期重新加载图像。

2 个答案:

答案 0 :(得分:3)

this不再是指$(" img")您需要将varialbe指定为this的占位符

$('img').error(function(){
    var $self = $(this);
    setTimeout(function(){
    $self.attr('src', $self.attr('src')+'?'+Math.random());
    }, 3000);
});

答案 1 :(得分:2)

this的值在内部函数范围内更改为window。 <> 1}}在触发外部函数时保存对jQuery包装器的引用。

image

修改
正如@epascarello指出的那样,当你追加$('img').error(function() { var $img = $(this); setTimeout(function(){ $img.attr('src', $img.attr('src') + '?' + Math.random()); }, 3000); }); 时,你假设图像上已经存在任何现有的查询参数。如果你知道情况总是如此,那很好,尽管参数确实应该是?randomNum。如果可能存在现有的参数,则您必须执行与以下类似的操作。 (但你真的需要在URL上附加一个随机数吗?)。

?key=randomNum

当您更新function updatedSrc(oldSrc) { var delim = (oldSrc.indexOf('?') != -1) ? '&' : '?'; return oldSrc + delim + "rand=" + Math.random(); } 时,您会src