我想更改图像路径目录,或者通过向父容器添加类来附加图像文件。
示例:如果我向父img
容器添加一个“large”类,我希望它附加img
文件名或更改img
路径。 / p>
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>
答案 0 :(得分:3)
例如,使用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);
});
});
答案 1 :(得分:1)
您可以使用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);
})