如何更改img src目录或图像文件名与jquery或PHP [英] How to change img src directory or image file name with jquery or PHP

查看:98
本文介绍了如何更改img src目录或图像文件名与jquery或PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to change the image path directory or append the the image file by adding a class to the parent container.

示例:如果我添加一个类大到父<@ c $ c> img 容器,我想它附加 img 文件名或更改 img 路径。

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.

   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>


推荐答案

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOfrel =nofollow> lastIndexOf

For example like this, using 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);
  });
});

这篇关于如何更改img src目录或图像文件名与jquery或PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆