将href中的图像替换为其他元素中的图像

Replace image in a href with image from another element

本文关键字:图像 其他 元素 替换 href      更新时间:2023-09-26

我想用img元素中的图像交换a元素中的图片。

我在类似的情况下用下面的脚本做到了这一点:

$('a.testColorbox.cboxElement img').each(function () {
var src = $(this).attr('src');
$(this).attr('src', src.replace("/70/70", "/640/480"));   
});

但是,由于该给定元素的文件结尾为~640~480~1,因此这不起作用。如何针对此元素?我有几个元素,其中相同的变量是文件结尾,所以我需要针对

70~70~1
640~480~1

HTML:

<li> 
  <a rel="colorboxRel-1637597101" href="/img/0~F76E4571-33C1-4CA6-A88C-0D8AFC3DCC6A~640~480~1" class="testColorbox cboxElement" onclick="return false;">    
  <img style="border-style:solid 1px;" src="/img/0~F76E4571-33C1-4CA6-A88C-0D8AFC3DCC6A~70~70~1" alt="Framsidan" title="Framsidan">  
  </a>
</li>

如果img的原始结尾始终是~70~70~1.jpg,则可以简化replace()调用,如下所示:

$('a.testColorbox.cboxElement img').each(function() {
    $(this).attr('src', function(i, src) {
        return src.replace("~70~70~", "~640~480~");
    });   
});