.href.代替给我双域名(http://localhosthttp://mydomain.com)


.href.replace giving me double domain (http://localhosthttp://mydomain.com)

我正在编写一段代码,其中我通过PHP使用file_get_contents从另一个服务器获取HTML。

然后一些链接需要得到原来的域名到它,以便他们链接到适当的地方,对于我的大多数链接我只是能够替换整行,因为他们是静态的,但这一个是动态的,我只需要替换它的一部分。

我是这样做的:

<script>$(document).ready(function(){
  $(".view").each(function(){
        this.href = this.href.replace("/tourney/", "http://binarybeast.com/tourney/");
    })
});</script>

然而,我得到的问题是,当这样做的时候,我得到双域,即使没有域是在第一个链接,像这样:

<a class="view" href="http://localhosthttp://binarybeast.com/tourney/load_match/169049">View Details</a>
原始:

<a class="view" href="/tourney/load_match/169049">View Details</a>

试试这个:

this.setAttribute("href",this.getAttribute("href").replace("/tourney/","http://.../"));

这将访问您编写的属性,而不是浏览器解析的属性。

使用attr("href")访问属性:

this.href = $(this).attr("href").replace(...)

或者不使用jQuery的getAttribute函数

href属性将始终返回绝对路径。下面是一个例子:

$("<a href='test'>")[0].href
//"http://stackoverflow.com/questions/15627830/href-replace-giving-me-double-domain-http-localhosthttp-mydomain-com/test"
$("<a href='test'>").attr("href")
//"test"

这里有一种稍微不同的方式来看待它:

$(document).ready(function(){
    $(".view").each(function(){
        var parts = this.href.split('/').slice(3);
        if (parts[0] == 'tourney') {
            this.href = '/' + parts.join('/');
        }
    });
});
http://jsfiddle.net/userdude/aAXYM/

这可以工作,因为this.href中的url将始终被扩展,因此您可以删除第一部分(域在parts[2]中),测试并重新组装。如果您想添加http://yoursite.com,只需将其添加到第一部分,作为'http://yoursite.com/' +或使用:

window.location.protocol + '//' + window.location.hostname + '/' + ... 

href属性返回完整的绝对url。要么将replace-regex更改为/.*?'/tourney'//,要么将其分配给host属性:

this.host = "binarybeast.com";