0

如果在我的主页中用 .jpg、.png 和 .js 为 Ex 的 url 自动替换 Scr 有一些图像链接 <img src="http://www.lx5.in/img/img.png"/>,它的自动转换为<img src="http://www.lx5.in.cdn.com/img/img.png"/> 是否可以使用任何 .js 脚本?谢谢

4

1 回答 1

1

这是解决您的问题的一种相对简单的方法:

function changeSrc (img) {
    // the file types you indicate you wanted to base the action upon:
    var fileTypes = ['png','jpg'],
        // gets the 'src' property from the current 'img' element:
        src = img.src,
        /* finds the extension, by splitting the 'src' by '/' characters,
           taking the last element, splitting that last string on the '.' character
           and taking the last element of that resulting array:
        */
        ext = src.split('/').pop().split('.').pop();
    // if that 'ext' variable exists (is not undefined/null):
    if (ext) {
        // iterates over the entries in the 'fileTypes' array:
        for (var i = 0, len = fileTypes.length; i < len; i++){
            /* if the 'ext' is exactly equal (be aware of capitalisation)
               to the current entry from the 'fileTypes' array:
            */
            if (ext === fileTypes[i]) {
                // finds the '.in/' string, replaces that with '.in.cdn.com/':
                img.src = src.replace(/.in\//,'.in.cdn.com/');
            }
        }
    }

}

// gets all the 'img' elements from the document:
var images = document.getElementsByTagName('img');

// iterates over all those images:
for (var i = 0, len = images.length; i < len; i++){
    // calls the function, supplying the 'img' element:
    changeSrc(images[i]);
}

JS 小提琴演示

参考:

于 2013-07-14T17:38:54.203 回答