2015-10-20 32 views
2

jQuery的刪除基本URL如果我有像利用鏈接

<a href="http://www.mywebsite.com/Scripts/xx.pdf>link1</a> 
<a href="http://www.mywebsite.com/Scripts/xx1.pdf>link2</a> 

的鏈接列表示例我怎麼能在頁面加載(jQuery的),在結尾處,刪除網站地址,所以只具有相對URL一樣

<a href="/Scripts/xx.pdf>link1</a> 
<a href="/Scripts/xx1.pdf>link2</a> 
+0

這個怎麼樣的解決方案: [轉換相對路徑絕對使用JavaScript(http://stackoverflow.com/questions/14780350 /轉換相對路徑絕對使用JavaScript) – AlexBerd

回答

1

還有就是代碼段共享,除去基本的URL here

function RemoveBaseUrl(url) { 
/* 
* Replace base URL in given string, if it exists, and return the result. 
* 
* e.g. "http://localhost:8000/api/v1/blah/" becomes "/api/v1/blah/" 
*  "/api/v1/blah/" stays "/api/v1/blah/" 
*/ 
var baseUrlPattern = /^https?:\/\/[a-z\:0-9.]+/; 
var result = ""; 

var match = baseUrlPattern.exec(url); 
if (match != null) { 
    result = match[0]; 
} 

if (result.length > 0) { 
    url = url.replace(result, ""); 
} 

return url; 
} 

你可以用callbac使用.attr()方法的k個功能:

$('a').attr('href',function(i,o){ 
    return RemoveBaseUrl(o) ; 
}); 

Working Demo

+1

[String.prototype.replace](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/替換)也接受一個正則表達式作爲第一個參數,所以你可以使用'url.replace(baseUrlPattern,「」)''。它可能更具可讀性? –

+0

這對於像https://hello-there.test.com/match這樣的URL不起作用(它返回「-there.test.com/match」) – Willster

0

請各位看看下面的代碼片段。爲了演示目的,我使用了href,從http://stacksnippets.net/開始。希望它能幫助你一點。

首先點擊「打印Href」按鈕查看原始href。然後點擊「從Href刪除基地」按鈕,該按鈕將更改href以從所有<a>標籤中刪除網站地址。然後點擊「打印HREF」按鈕,再點擊查看修訂href

$(document).ready(function(){ 
 
    $("#printHref").click(function(){ 
 
    $("#link1href").text($($("a")[0]).attr("href")); 
 
    $("#link2href").text($($("a")[1]).attr("href")); 
 
    }); 
 

 
    $("#changeHref").click(function(){ 
 
    $("a").each(function(){ 
 
     var websiteName = window.location.host; 
 
     var partToReplcae = "http://"+websiteName; 
 
     $(this).attr("href",$(this).attr("href").replace(partToReplcae,"")); 
 
    }); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<a href="http://stacksnippets.net/Scripts/xx.pdf">link1</a> 
 
<a href="http://stacksnippets.net/Scripts/xx1.pdf">link2</a> 
 
<br/><br/> 
 
<button id="printHref" >Print Href</button><button id="changeHref" >Remove base from Href</button> 
 
<br/> 
 
Link1 Href:<p id="link1href"></p> 
 
Link2 Href:<p id="link2href"></p>