繁体   English   中英

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

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

我正在处理一段代码,其中我使用file_get_contents通过php从另一台服务器获取html。

然后某些链接需要将原始域放置到其上,以便它们链接到适当的位置,因为我的大多数链接ive都能够替换整行,因为它们是静态的,但是由于这是动态的,因此我需要替换只是一部分。

我已经这样完成了:

<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>

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

尝试这个:

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

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

这是一种稍微不同的查看方式:

$(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是因为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";

暂无
暂无

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

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