我需要一些JS / jquery(jquery首选)的帮助,它可以替换匹配特定模式的站点上的所有图像。在页面上,我们的图像看起来像:
img src="http://a248.e.akamai.net/a/262/9086/10h/origin-d9.scene7.com/is/image/default/**A34567_v1**?wid=570&hei=413&fmt=jpeg&qlt=92,0&resMode=sharp2&op_usm=1.1,0.5,1,0"
如果图像src包含“_v1”,我想将该字符串更改为“_v2”。使用上面的示例,最终结果将是:
img src="http://a248.e.akamai.net/a/262/9086/10h/origin-d9.scene7.com/is/image/default/**A34567_v2**?wid=570&hei=413&fmt=jpeg&qlt=92,0&resMode=sharp2&op_usm=1.1,0.5,1,0"
这可能会在页面上多次发生。有人可以帮忙吗?
谢谢!
答案 0 :(得分:1)
由于您没有提供多个示例,我无法分辨您想要使用的模式。但是,我创建了一个带有正则表达式的简化版本,以便以正确的方式指出:
考虑这个HTML:您想要将所有旧的更改为新的。
<img src="/old_a.png" />
<img src="/new_b.png" />
<img src="/old_c.png" />
你可以使用jQuery循环遍历所有img标签:
$("img").each(function(i, element){
var pattern = /[old]/; //A regular expression that you'll have to modify to your needs
var src = $(element).attr("src");
if(pattern.test(src))
$(element).attr("src", src.replace("old", "new"));
});
基本上它的作用是它将正则表达式应用于每个图像元素。但是,您必须自己创建该正则表达式。
答案 1 :(得分:0)
这可能会这样做:
$(function(){
$('img').each(function(index, img){
$(this).attr('src', $(this).attr('src').replace('_v1**', '_v2**'));
});
});