简体   繁体   English

如何根据两个不同的环境更改images src属性?

[英]How do I change an images src attribute depending on two different environments?

I have a HTML page which contain a collection of images which all have a specific path prefixed to them, img . 我有一个HTML页面,其中包含图像集合,所有图像都有一个前缀为img的特定路径。

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

I have a loop which goes through the collection of images: 我有一个遍历图像集合的循环:

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/');
    }
}

Now this works perfectly locally however when I run this on my company's QAF server, it appears the server is adding a dev path: 现在,它可以在本地完美运行但是当我在公司的QAF服务器上运行该服务器时,该服务器似乎正在添加开发路径:

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

Thus when my if block fires: 因此,当我的if块触发时:

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

I will get : 我会得到 :

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

Is there a way I test for both environments? 我有两种方法都可以测试吗?

Thanks in advance! 提前致谢!

UPDATE Oscar kindly added a solution involving location.protocol and location.host This is what I came up with: UPDATE奥斯卡好心地添加了一个涉及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/');
            }
    }

But that doesn't work. 但这是行不通的。 In his answer he did away with the .replace method, but looks like he forgot a piece. 在他的回答中,他取消了.replace方法,但看起来好像他忘记了一块。 Can anyone help me get it over the finish line? 谁能帮我超过终点线吗?

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

You could use : 您可以使用:

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

Prepending hostname and protocol to to your images folder variable will make it machine agnostics. 将主机名和协议添加到images文件夹变量将使它成为不可知论的机器。

Also, if you have some kind of config system in your application, add this value as a settable key in that config system. 另外,如果您的应用程序中有某种配置系统,请将此值添加为该配置系统中的可设置键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM