我正在从API中检索一些图像并将它们更改为我自己的图像,如下所示:
$('img[src="http://www.example.com/dir/images/dir/1.gif"]').attr('src', "http://cdn.example.com/dir/1.gif");
$('img[src="http://www.example.com/dir/images/dir/2.gif"]').attr('src', "http://cdn.example.com/dir/2.gif");
$('img[src="http://www.example.com/dir/images/dir/3.gif"]').attr('src', "http://cdn.example.com/dir/3.gif");
$('img[src="http://www.example.com/dir/images/dir/4.gif"]').attr('src', "http://cdn.example.com/dir/4.gif");
$('img[src="http://www.example.com/dir/images/dir/5.gif"]').attr('src', "http://cdn.example.com/dir/5.gif");
$('img[src="http://www.example.com/dir/images/dir/6.gif"]').attr('src', "http://cdn.example.com/dir/6.gif");
$('img[src="http://www.example.com/dir/images/dir/7.gif"]').attr('src', "http://cdn.example.com/dir/7.gif");
$('img[src="http://www.example.com/dir/images/dir/8.gif"]').attr('src', "http://cdn.example.com/dir/8.gif");
$('img[src="http://www.example.com/dir/images/dir/9.gif"]').attr('src', "http://cdn.example.com/dir/9.gif");
$('img[src="http://www.example.com/dir/images/dir/10.gif"]').attr('src', "http://cdn.example.com/dir/10.gif")
现在,因为有太多的文字我压缩了如下:
$('img[src^="http://www.example.com/"]').each(function(index,element){
var $this, src, newSrc;
$this = $(this);
src = $this.attr('src');
newSrc = src.replace('www.example.com/dir/images/dir', 'cdn.example.com/dir');
$this.attr('src', newSrc);
});
现在,我想将图片扩展名更改为.png
。所以基本上我想替换每个图像和从[{1}}到.gif
的扩展名的网址。
我怎样才能做到这一点?
答案 0 :(得分:2)
怎么样:
$('img[src^="http://www.example.com/"]').each(function(i, value) {
$(this).attr('src', $(this).attr('src').replace('www.example.com/dir/images/dir', 'cdn.example.com/dir').replace('.gif', '.png'));
});
答案 1 :(得分:1)
$('img[src^="http://www.example.com/"]').attr('src', function() {
return this.src
.replace('www.example.com/dir/images/dir', 'cdn.example.com/dir')
.replace('.gif', '.png');
});
答案 2 :(得分:0)
newSrc.replace(".gif",".png");
认为这样可以解决问题:)