Javascript 查找&;替换'的部分文件路径;src&x27;属性
假设我有一个主题切换器,并且有多个图像/图标Javascript 查找&;替换'的部分文件路径;src&x27;属性,javascript,jquery,Javascript,Jquery,假设我有一个主题切换器,并且有多个图像/图标 <img src="images/icons/icon-1.png"> <img src="images/icons/icon-2.png"> <img src="images/icons/icon-3.png"> <img src="images/icons/icon-4.png"> 如果我再次单击以选择另一种颜色,例如“红色”,则路径将变成如下所示 <img src="images/icon
<img src="images/icons/icon-1.png">
<img src="images/icons/icon-2.png">
<img src="images/icons/icon-3.png">
<img src="images/icons/icon-4.png">
如果我再次单击以选择另一种颜色,例如“红色”,则路径将变成如下所示
<img src="images/icons/red/blue/icon-1.png">
<img src="images/icons/red/icon-1.png">
本来应该是这样的
<img src="images/icons/red/blue/icon-1.png">
<img src="images/icons/red/icon-1.png">
如何使用“替换方法”查找和覆盖旧路径,而不更改文件名“icon-1.png”,例如,因为它是一个动态图标
提前感谢。您需要循环并替换每个元素的
src
$('img').attr('src', function(i, src){
return src.replace('images/icons', 'images/icons/blue')
});
使用getter版本的
.attr()
时,它将返回匹配元素集中第一个元素的属性值,因此将为所有元素设置相同的值。只需首先从源代码获取文件名,然后重写整个源代码。假设您以“主题”的形式向changeTheme函数发送以下值中的内容:“图像/图标”、“图像/图标/蓝色”、“图像/图标/红色”等。这样就可以了
function changeTheme(theme) {
var img=$(img);
var filename=img.attr('src').split('/');
filename=filename[filename.length-1];
img.attr('src',theme+"/"+filename);
}
或者,如果您不介意将文件名存储为图像的数据属性,则可以更改函数的第二行和第三行,其中包括:
var filename=img.data("filename"); //assuming you are storing the file name in data-filename attribute
名字总是一样的吗?在这种情况下,您可以使用以下代码
$('img').attr('src', function(i, src){
return 'images/icons/blue/' + src.split("/").pop()
});
谢谢你的支持!谢谢你的支持!