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