简体   繁体   English

查找并替换“ src”属性的部分文件路径

[英]find & replace part of file path for 'src' attribute

Assuming I have a theme switcher, and there're multiple images/icons 假设我有一个主题切换器,并且有多个图像/图标

<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">

And also I have another set of these icons with a different color/path 而且我还有另一组带有不同颜色/路径的图标

<img src="images/icons/blue/icon-1.png">
<img src="images/icons/blue/icon-2.png">
<img src="images/icons/blue/icon-3.png">
<img src="images/icons/blue/icon-4.png">

the below jQuery code working perfectly when I click to change theme color for 'once' 当我单击更改“一次”的主题颜色时,下面的jQuery代码可以正常工作

$('img').attr('src', $('img').attr('src').replace('images/icons', 'images/icons/blue'));

If I clicked again to choose another color say 'red', the path become like this 如果我再次单击以选择另一种颜色,例如“红色”,则路径变成这样

<img src="images/icons/red/blue/icon-1.png">

while it's supposed to be like this 虽然应该是这样

<img src="images/icons/red/icon-1.png">

how I can make 'replace method' to find & overwrite old path WITHOUT change file name 'icon-1.png' for example, as it's a dynamic icons. 例如,我如何使“替换方法”查找并覆盖旧路径而无需更改文件名“ icon-1.png”,因为它是动态图标。

Thanks in advance. 提前致谢。

Is the name always the same? 名字总是一样的吗? in that case you can use the following code 在这种情况下,您可以使用以下代码

$('img').attr('src', function(i, src){
    return 'images/icons/blue/' + src.split("/").pop()
});

You need to loop and replace the src of each element. 您需要循环并替换每个元素的src

$('img').attr('src', function(i, src){
    return src.replace('images/icons', 'images/icons/blue')
});

When you use the getter version of .attr() it will return the attribute value of the first element in the matched element set, so the same value will get set for all elements. 使用.attr()的getter版本时,它将返回匹配的元素集中第一个元素的属性值,因此将为所有元素设置相同的值。

Just get the filename from the source first, then rewrite the whole source. 只需先从源文件中获取文件名,然后重写整个源文件即可。 Assuming that you send as "theme" to changeTheme function, something from the following values: "images/icons", "images/icons/blue", "images/icons/red", etc. this will do the trick. 假设您以“主题”形式发送以更改主题功能,则需要以下值:“图像/图标”,“图像/图标/蓝色”,“图像/图标/红色”等。

function changeTheme(theme) {
 var img=$(img);
 var filename=img.attr('src').split('/');
 filename=filename[filename.length-1];
 img.attr('src',theme+"/"+filename);
}

Or if you don't minde storing the file name as a data attribute to the image, you can change the second and third lines of the functions, with something along the lines of: 或者,如果您不介意将文件名存储为图像的数据属性,则可以更改函数的第二行和第三行,其中包括:

var filename=img.data("filename"); //assuming you are storing the file name in data-filename attribute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM