javascript 如何使用 jquery 或 PHP 更改 img src 目录或图像文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12962818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change img src directory or image file name with jquery or PHP
提问by Taylor
I would like to change the image path directory or append the the image file by adding a class to the parent container.
我想通过向父容器添加类来更改图像路径目录或附加图像文件。
Example: If I add a class of "large" to the parent img
container, I would like it to either append the img
file name or change the img
path.
示例:如果我向父img
容器添加“大”类,我希望它附加img
文件名或更改img
路径。
src="/images/services/image.jpg" changed to src="/images/services/image-large.jpg"
or
src="/images/services/image.jpg" changed to src="/images/services/large/image.jpg"
...............................................................................
default, no class:
<div>
<img src="/images/services/image.jpg" alt="" />
</div>
Option 1, with class:
<div class="large-image">
<img src="/images/services/image-large.jpg" alt="" />
</div>
Option 2, with class:
<div class="large-image">
<img src="/images/services/large/image.jpg" alt="" />
</div>
回答by mplungjan
For example like this, using lastIndexOf
例如像这样,使用lastIndexOf
$function() {
var img = $(".large-image > img").each(function() { // for each img found
var src = $(this).attr("src"); // get the src
var path = src.substring(0,src.lastIndexOf('/')); // get the path from the src
var fileName = src.substring(src.lastIndexOf('/')); // and filename
var newSrc = path+"/large"+fileName; // re-assemble
// or change filename:
// var newSrc = path+"/"+fileName.replace(".jpg","-large.jpg"); // re-assemble
$(this).attr("src",newSrc);
});
});
回答by user1026361
you can use jquery to change the src, split it, and add your new folder
您可以使用 jquery 更改 src、拆分它并添加新文件夹
<div class="large-image">
<img src="/images/services/image.jpg" alt="" />
</div>
$('.large-image > img').each(function(){
var msrc=$(this).attr('src');
msrc=msrc.split('/'); //images, services, image.jpg
var lastelem = msrc.pop(); //images, services // lastelem: image.jpg
msrc.push('large'); //images, services, large // lastelem: image.jpg
msrc.push(lastelem); //images, services, large, image.jpg
msrc=msrc.join('/'); //"images/services/large/image.jpg"
$(this).attr('src', msrc);
})