2014-08-27 70 views
-4

我只是想在加載頁面時更改所有的href鏈接。使用JavaScript或JQuery或任何其他方法。如何更改頁面中所有鏈接的href?

我的一個頁面上的鏈接都喜歡

<a href="http://example.com/book"> 
<a href="http://example.com/sheo"> 
<a href="http://example.com/belt"> 

進入

<a href="http://a.example.com/book"> 
<a href="http://a.example.com/sheo"> 
<a href="http://a.example.com/belt"> 

是否有可能使用替代(我只是猜測)? 請同時查看查詢字符串如何不更改,只更改主機名稱。 抱歉有混淆。

+1

你的意思是,如果你有通過'http://cnn.com'你想把它改成'http:// a.cnn.com',或者是'http:// example.com',因爲我想知道這些答案是否會跳過槍? – Andy 2014-08-27 09:38:37

+1

那麼,例如,指向'http:// m.example.com /'的鏈接呢?作爲一個附錄,對於這個問題,我不知道是否應該冷靜下來*所有事情*,或者投票表決爲「不清楚你要問什麼」。 – 2014-08-27 09:39:26

+1

我去投票保留;似乎不公平懲罰那些試圖幫助解決不明確問題的人。 – 2014-08-27 09:43:35

回答

0

這改善了Jhecht的答案,讓你同時保持第二部分更換URL的第一部分:

$('a').each(function(i,link){ 
    var reg = /(http:\/\/example.com\/)(.*)/ 
    var newlink = link.href.replace(reg, 'http://m.example.com/$2') 
    link.href = newlink; 
    link.innerHTML = newlink; 
}); 

DEMO

+0

你的答案是非常接近我想,我使用 test1 test2 Racheal 2014-08-27 10:34:29

+0

@Racheal,我已經更新了我的答案來取代鏈接文本太多,如果這就是你以後是什麼也。 – Andy 2014-08-27 10:38:22

+0

你好安迪,我已經實現了你的代碼,它沒有工作,我已經檢查了所有的代碼,一次又一次,即使在簡單的測試文件,它沒有工作,我也使用最新的jquery文件。 – Racheal 2014-08-27 10:46:48

0

嘗試用在文件準備功能,下面的jQuery代碼:

$(document).ready(function() { 
    $('a').attr('href', 'http://a.example.com'); 
    }); 
+0

不需要循環每個'a'元素。 – 2014-08-27 09:38:48

0

做得一樣:

$('a').attr('href','http://a.example.com'); 

就是這樣。

0

使用jQuery:

$("a").attr("href", "http://a.example.com"); 

或者,如果你希望這些鏈接到http://example.com

$('a[href="http://example.com"]').attr("href", "http://a.example.com"); 
0

嘗試:

$(document).ready(function() { 
$('a[href*="Yourpage.html"]').prop('href' , 'http://a.example.com'); 
}); 
1

應該做你想要什麼,並留下完整地跟蹤請求的鏈接。

$('a').each(function(i,link){ 
    link.href = link.href.replace('http://example.com/','http://a.example.com/'); 
}); 
+1

我認爲這應該做你的工作.. – 2014-08-27 09:41:35

+0

但如何更改與查詢字符串。 http://example.com/college_bookstore/textbook/,也有很多不同的查詢字符串的鏈接,但具有相同的基礎url示例。com – Racheal 2014-08-27 09:55:02

+1

如果您嘗試將其中包含「http:// example.com /」的網站中的所有鏈接更改爲「http:// a.example.com /」,那麼是的,這是應該管用。沒有更多的細節,我不能更具體地解決你的問題。 – Jhecht 2014-08-27 10:05:56

相關問題