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

时间:2013-03-26 01:35:06

标签: php javascript jquery replace

我在处理一段代码,我通过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>

4 个答案:

答案 0 :(得分:0)

使用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"

答案 1 :(得分:0)

试试这个:

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

这会在您编写属性时访问该属性,而不是浏览器解析的属性。

答案 2 :(得分:0)

这是一种略微不同的观察方式:

$(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中的网址将始终展开,因此您可以删除第一部分(域位于parts[2]),测试和重新组合。如果您想添加http://yoursite.com,只需将其添加到第一部分,'http://yoursite.com/' +或使用:

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

如果合适的话。

答案 3 :(得分:0)

href属性返回完整的绝对网址。将替换正则表达式更改为/.*?\/tourney\//,或者指定给host property

this.host = "binarybeast.com";