如何使用jquery或PHP更改img src目录或映像文件名

时间:2012-10-18 20:04:09

标签: javascript jquery html css

我想更改图像路径目录,或者通过向父容器添加类来附加图像文件。

示例:如果我向父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>

2 个答案:

答案 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);
})