使用JavaScript获取绝对路径

问题描述:

在我的代码的某些部分中,我有这个

In some part of my code I have this

while(document.images[local].src != imgV)



因此,我以这种方式引用图像:



So, I refer to the images this way:

vermelhaColocada.src = "imagens/something.gif";



但是出于某种原因,document.images.src指向绝对URL路径(http://localhost/..../images/something.gif).

这对我来说是个问题,因为我必须与手动分配的变量进行比较:



But for some reason, document.images.src refers to the absolute URL path (http://localhost/..../images/something.gif).

This is a problem for me because I have to compare with a variable assigned manually:

var imgV = "http://localhost/..../imagens/something-2.gif";



因此,如果我没有运行localhost(或我在该变量上定义的任何内容),则该Web应用程序将无法正常运行(每次我远程执行该应用程序时都必须进行更改).

因此,我想解决方案将是获取URL绝对路径,分配给变量,然后与"images/something.gif-2"连接.

所以我的问题是,我该怎么做?还有其他解决方案吗?



So if I''m not running localhost (or anything I define on that variable), the web app will not work properly (i have to change everytime I execute the app remotely or something).

So I suppose the solution would be getting the URL absolute path, assign to a variable, and then join with "images/something.gif-2".

So my question is, how can I do that? There''s any other solution?

这是我在网页上使用的:

This is what I use on my web page:

function GetSiteRoot()
{
    var rootPath = window.location.protocol + "//" + window.location.host + "/";
    if (window.location.hostname == "localhost")
    {
        var path = window.location.pathname;
        if (path.indexOf("/") == 0)
        {
            path = path.substring(1);
        }
        path = path.split("/", 1);
        if (path != "")
        {
            rootPath = rootPath + path + "/";
        }
    }
    return rootPath;
}



我只是将所需的路径/文件名添加到返回的内容中,并且我有一个完全解析的URL.



I simply add the desired path/filename to what''s returned, and I have a fully resolved URL.