如何根据两种不同的环境更改图像src属性?

时间:2016-09-13 14:25:08

标签: javascript

我有一个HTML页面,其中包含一组图像,这些图像都有一个特定的路径作为前缀, img

<img src="img/foo.gif" >
<img src="img/bar.gif" >
<img src="img/baz.gif" >

我有一个遍历图像集的循环:

container_images = container.getElementsByTagName('img');
             imgSrc = /img\//gi,

for (var i = 0; i < container_images.length; i++) {
    var images = container_images[i];

    if (images.src.indexOf('img') !== -1) {
        images.src = images.src.replace(imgSrc, 'new/path/here/');
    }
}

现在这完全可以本地,但是当我在公司的QAF服务器上运行时,服务器似乎正在添加开发路径:

<img src="http://ryelxusecqcm1.rye.com:8080/us-home/tools/img/foo.gif">

因此当我的if块触发时:

if (images.src.indexOf('img') !== -1) {
    images.src = images.src.replace(imgSrc, 'new/path/here/');
}

我会得到:

<img src="http://ryelxusecqcm1.rye.com:8080/us-home/tools/new/path/here/foo.gif">

我是否有办法测试这两种环境?

提前致谢!

更新 Oscar慷慨地添加了一个涉及location.protocollocation.host的解决方案。这就是我想出来的:

var root = location.protocol + '//' + location.host + '/',
           emailUrl = /img/gi,
           ewemailUrl = root + emailUrl;

    for (var i = 0; i < container_images.length; i++) {
            var images = container_images[i];

            if (images.src.indexOf('img') !== -1) {
                images.src = images.src.replace(newemailUrl, '/new/path/here/');
            }
    }

但这并不奏效。在他的回答中,他取消了.replace方法,但看起来他忘了一块。任何人都可以帮助我完成终点线吗?

if (images.src.indexOf('img') !== -1) {
    images.src = images.src = location.protocol + '//' + location.host +  'new/path/here/');
}

1 个答案:

答案 0 :(得分:1)

您可以使用:

if (images.src.indexOf('img') !== -1) {
    images.src = images.src = location.protocol + '//' + location.host +  'new/path/here/');
}

将主机名和协议预先添加到images文件夹变量将使其成为机器不可知。

此外,如果您的应用程序中有某种配置系统,请将此值添加为该配置系统中的可设置键。