使用按钮刷新任意图像

Refresh an arbitrary image with a button

本文关键字:任意 图像 刷新 按钮      更新时间:2023-09-26

>我有一个自动生成的表单,它也很容易显示缩略图。我想在图像旁边添加一个按钮,如果更新,它将刷新它。我想考虑缓存的图像。

我很容易添加一个按钮:

// add a refresh button to image previews
$('a[href*="/thumbs/"]').after('<div class="refresh-image"><button class="refresh-image-button">Refresh</button></div>');

由于如果刷新按钮刷新所有过时的图像,我可以接受,因此我尝试将查询字符串附加到图像 src(如果存在,请删除旧的查询字符串):

// attach refresher to button
$(".refresh-image-button").click(function() {
    $('img[src*="/thumbs/"]').attr("src", $(this).attr("src").split('?',1)+'?'+Date.now());
});

但是,我真的不能这样做,因为这里的 $(this) 不引用匹配的图像,无论如何我都无法在此 jquery 匹配中执行拆分操作。

怎么做?

作为奖励,如果有人有体面的自动刷新图像代码的参考,那将很有帮助。

这基于此处更简单的SO查询。

遍历集合:

$(".refresh-image-button").click(function() {
    $('img[src*="/thumbs/"]').each(function() {
        $(this).attr("src", $(this).attr("src").split('?',1)+'?'+Date.now());
    });
});

http://jsfiddle.net/g68gxu93/1/

您可以使用新的尾随参数单独生成一个变量,例如:

$(".refresh-image-button").click(function() {
    var newAttr = $('img[src*="/thumbs/"]').attr("src").split("?")[0] + "?ver=" + new Date().getTime();
    $('img[src*="/thumbs/"]').attr("src", newAttr);
});

参见 JSFIDDLE

我最终做了一些几乎完全像@Moogs答案的事情。

addRefreshButtons();
// NICEITIES
function addRefreshButtons() {
  // add a refresh button to image previews
  $("div.refresh-image").remove();
  $('a[href*="/thumbs/"]').after('<div class="refresh-image"><button class="refresh-image-button">Refresh</button></div>');
  // attach refresher to button
  $(".refresh-image-button").click(function() {
      refreshThumbnails();
  });
}
function refreshThumbnails() {
    $('img[src*="/thumbs/"]').each(function() {
        var src = $(this).attr('src');
        var newSrc = src.split('?',1)+'?'+Date.now()
        $(this).attr('src', newSrc);
    });
}